How do I populate TextBox fields from a ComboBox selection? - c#

I am in the process of building a Drone Pilot logbook. In the logbook, on the Pilots page, you select from a comboBox at the top to choose your pilot. This data is taken from a SQL Server (.MDF) database file in the project. Once you have chosen the pilot, existing data from the database populates the rest of the form. The code I have below queries the SQL Server database file successfully and shows the FullName in the comboBox, but now I'm at a blank as far as how I get the rest of the form to fill out (i.e. FirstName, LastName, Address, City, etc.)
private void frmPilots_Load(object sender, EventArgs e)
{
using (SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Kevin\ownCloud\Programming\C# Projects\DroneLogbook\DroneLogbook\data.mdf;Integrated Security=True;Connect Timeout=30"))
{
SqlCommand sc = new SqlCommand("select Id,FullName from Pilots", conn);
conn.Open();
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(string));
dt.Columns.Add("FullName", typeof(string));
dt.Load(reader);
cmbExistingPilot.ValueMember = "Id";
cmbExistingPilot.DisplayMember = "FullName";
cmbExistingPilot.DataSource = dt;
conn.Close();
}

You need another select statement based on the selected value of your ComboBox and a SqlDataReader to fill out your TextBoxes. Something like this:
SqlCommand command = new SqlCommand(
"SELECT FirstName, LastName FROM Pilots where Id = #Id;",
connection);
command.Parameters.AddWithValue("#Id",cmbExistingPilot.SelectedValue.ToString());
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
txtFirstName.Text = reader.GetString(0);
txtLastName.Text = reader.GetString(1);
//and...
}
}

Related

how to populate a datagridview based on selected row

I'm trying to populate a datagridview based on the selected row in another, as an object kind of.
public Form1()
{
dg1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
Allemployees(dg1);
}
The following function is returning all employees to the first dg
private void Allemployees(DataGridView dg)
{
conn.Open();
SqlCommand cmd = new SqlCommand("select * from emp", conn);
SqlDataReader reader = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(reader);
dg.DataSource = table;
conn.Close();
}
How do i use selected row as an object and pass it to return emp_loc relations
private void locsbyemp(DataGridView dg, int emp_id)
{
conn.Open();
SqlCommand cmd = new SqlCommand(#"select loc_name From emp_locs WHERE emp_id = #emp", conn);
cmd.Parameters.AddWithValue("#emp", emp_id);
SqlDataReader reader = cmd.ExecuteReader();
DataTable table = new DataTable();
table.Load(reader);
dg.DataSource = table;
conn.Close();
}
same thing with trying to populate "edit emp form" controls with selected row data
Thanks in advance

Updating Data GridView using the selected value inside the dropdown list

I have a dropdownlist and a gridview.. Dropdown list contains the list of the tables I have in my database. What I want is, when I select a particular table name from the dropdownlist, I want all the columns and data inside that particular table display inside the gridview.
This is my code...
Code for displaying the list of tables inside the dropdown is success.. But to bind the columns and data inside the gridview is not success..
Please Help me...
protected void Page_Load(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT table_name FROM INFORMATION_SCHEMA.TABLES", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
DropDownList1.DataSource = ds;
DropDownList1.DataTextField = "table_name";
DropDownList1.DataValueField = "table_name";
DropDownList1.DataBind();
con.Close();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
using (SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS;Initial Catalog=Employee;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM INFORMATION_SCHEMA.columns where table_name='+ DropDownList1.selecteditem.text +'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
//+DropDownList1.selecteditem.text +
GridView1.DataBind();
con.Close();
}
}
This is a bad idea on several levels. First you are wide open to SQL injection. Second, you are giving everyone full view access to every column and row of every table.
But the reason you are not getting data is because the select string does not make sense. It should look like this
"SELECT * FROM INFORMATION_SCHEMA.columns where table_name='" + DropDownList1.SelectedValue + "'"
But this is how a proper sql connection should look like.
//create a new datatable
DataTable dt = new DataTable();
//create the string that hold the query including token
string query = "SELECT * FROM INFORMATION_SCHEMA.columns where table_name = #TableName";
//create a new database connection
using (SqlConnection connection = new SqlConnection(ConnectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
command.CommandType = CommandType.Text;
//replace the token with the correct value
command.Parameters.Add("#TableName", SqlDbType.VarChar).Value = DropDownList1.SelectedValue;
//open the connection
connection.Open();
//load the data of the select into the datatable
dt.Load(command.ExecuteReader());
//bind the datatable to the gridview
GridView1.DataSource = dt;
GridView1.DataBind();
//but you can also skip the datatable and bind directly to the gridview
GridView1.DataSource = command.ExecuteReader();
GridView1.DataBind();
}

population of texboxes when combobox selected item is changed

Hello all I am trying to populate some textboxes automatically when I select an item from a combobox dropdown list using Microsoft sql server with a usercontrol form. I have written the codes below, however I am getting the items in the combox dropdown list but when I select an item in the combobox dropdown list, nothing happens in the text boxes. the values are in a table called competitors. the columns are Institution, Region, FirstName, LastName and I want the values to display in the respective textboxes when I select the combox dropdown. I seek your assistance in solving this problem. thanks in advance
private void RabbitCare_Load(object sender, EventArgs e)
{
CBoxParishDdlist.Items.Clear();
SqlConnection connect = new SqlConnection(#"Data Source=ITSPECIALIST\SQLPROJECTS;Initial Catalog=EXPRORESULTS;Integrated Security=True ");
connect.Open();
SqlCommand cmd = connect.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select ParishName FROM Competitors WHERE CompetitiveEventName = 'Care and Management of Bees'";
cmd.ExecuteNonQuery();
DataTable dat = new DataTable();
SqlDataAdapter SDA = new SqlDataAdapter(cmd);
SDA.Fill(dat);
foreach (DataRow DAR in dat.Rows)
{
CBoxParishDdlist.Items.Add(DAR["ParishName"].ToString());
}
connect.Close();
}
private void CBoxParishDdlist_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection connect = new SqlConnection(#"Data Source=ITSPECIALIST\SQLPROJECTS;Initial Catalog=EXPRORESULTS;Integrated Security=True ");
connect.Open();
cmd = new SqlCommand("SELECT * FROM Competitors WHERE ParishName = '" + CBoxParishDdlist.Text + "'", connect);
cmd.ExecuteNonQuery();
SqlDataReader dr;
dr = cmd.ExecuteReader();
while (dr.Read())
{
string Institution = (string)dr["Institution"].ToString();
TxtBoxInstitution.Text = Institution;
string Region = (string)dr["Region"].ToString();
TxtBoxRegion.Text = Region;
string FirstName = (string)dr["FirstName"].ToString();
TxtBoxFname.Text = FirstName;
string LastName = (string)dr["LastName"].ToString();
TxtBoxLname.Text = LastName;
}
connect.Close();
I think this will solve your problem.
TxtBoxInstitution.Text = comboBoxName.SelectedItem.ToString();

inserting id corresponding to a item in combobox in database using c#.net

private void Form1_Load(object sender, EventArgs e)
{
string Sql = "select project_name from tb_project";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(Sql, con);
con.Open();
OleDbDataReader DR = com.ExecuteReader();
while (DR.Read())
{
combo_status.Items.Add(DR[0]);
}
con.Close();
}
in this code i am fetching project name from a table in database and showing them in combobox but what i want is that in this is that in the table from where i am fetching project name there is a project id corresponding to that name...so i want project name to be displayed in combox and when i click on submit then it should insert project id corresponding to the project name choosen in combobox so how can i do that.....
Try this :
string Sql = "select project_name, project_id from tb_project";
con = new OleDbConnection(constr);
com = new OleDbCommand(Sql, con);
con.Open();
OleDbDataReader DR = com.ExecuteReader();
DataTable table = new DataTable();
table.Load(dr);
combo_status.DataSource = table;
combo_status.DisplayMember = "project_name";
combo_status.ValueMember= "project_id";
As per my understanding, you want to insert the project id of the selected project name in some other table. To accomplish this you can use following code:
private void Form1_Load(object sender, EventArgs e)
{
string Sql = "select project_id, project_name from tb_project";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand com = new OleDbCommand(Sql, con);
con.Open();
DataSet ds = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(com);
da.Fill(ds);
combo_status.DataSource = ds.Tables[0];
combo_status.DisplayMember = "project_name";
combo_status.ValueMember = "project_id";
com.Dispose();
con.Close();
}
In this way you will find the project name using combo_status.SelectedText and you will find the project id using combo_status.SelectedValue. Now you can use it anywhere you want.
Use DisplayMember and ValueMember Of Combobox
// Fetch Both Project Name and Project Id
string Sql = "select project_name, project_id from tb_project";
con = new OleDbConnection(constr);
com = new OleDbCommand(Sql, con);
con.Open();
OleDbDataReader DR = com.ExecuteReader();
DataTable dt;
dt.Load(Dr);
combo_status.DataSource = dt; //Check it this works or not
combo_status.DisplayMember = "project_name";
combo_status.ValueMember= "project_id";
To get Project_id of Selected project_name
Int64 varproject_Id = Convert.ToInt64(combo_status.SelectedValue);
try this
while (DR.Read())
{
combo_status.Items.Add(DR.GetValues(0).toString());
}

How to populate data from SQL Server database columns to textboxes

I want to populate data from a SQL Server database from many columns to many textboxes .. I have a code to populate just one box .. can someone edit my code... I want to pull data and show it in Name, Address, Telephone No and Date ... plz help .. this code works for only one textbox..
Thanks in advance
SqlConnection Conn = new SqlConnection(#"Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True");
SqlCommand Comm1 = new SqlCommand("Select * From PersonalUsers ", Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
if (DR1.Read())
{
Name.Text = DR1.GetValue(0).ToString();
}
while (DR1.Read())
{
if(DR1.GetName() == "YourSQLColumnName")
{
YourTextBox.Text = (string) DR1["YourSQLColumnName"];
}
// Your Other textboxes and columns which you want to match should follow as this template
}
SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sql, _conn);
SqlDataReader rdr = cmd.ExecuteReader();
System.Data.DataTable tbl = new System.Data.DataTable("Results");
tbl.Load(rdr);
if (tbl.Rows.Count > 0)
Name.Text = tbl.Rows[0]["column_name"].ToString();
string cs=System.Configuration.ConfigurationManager.ConnectionString["DBCS"].ConnectionString;
using(OracleConnection con=new OracleConnection(cs))
{
sql="select empname from Emp where empno='"+empno+"'";
OracleCommand cmd = new System.Data.OracleClient.OracleCommand(sql,con);
con.Open();
OracleDataReader rdr = cmd.ExecuteReader();
if(rdr.Read())
{
EmpName.Text=Convert.ToString(rd["empname"]);
}
}
I assume that you would like to take care of both more rows and more columns.
Try to specify the columns. It works without, but the performance is better if you do so.
I assume you have a class called PersonalUser with the specifed properties.
It is also nice to have it in an sorted order, so I added that
public List<PersonalUser> FetchMyData()
{
SqlConnection Conn = new SqlConnection(#"Data Source=rex;Initial Catalog=PersonalDetails;Integrated Security=True");
SqlCommand Comm1 = new SqlCommand("Select Name, Address, TelephoneNo,Date From PersonalUsers order by Name", Conn);
Conn.Open();
SqlDataReader DR1 = Comm1.ExecuteReader();
var result = new List<PersonalUser>();
while (DR1.Read())
{
result.Add(new PersonalUser {
Name = DR1.GetString(0);
Address= DR1.GetString(1);
TelephoneNo = DR1.GetString(2);
Date = DR1.GetString(3)
}
);
}
return result;
}
I would also, if the need is getting much complex than this, conidering using Entity Framwork..

Categories