This example below is not exactly solves your issue but it:
- Shows appropriate way of using disposable objects such as
SqlConnection
and SqlCommand
- shows that you don't need to load Dataset, DataTable is enough in many cases
- shows how to bind
textbox
to data
Using this, you can imagine, how easy would be to load another DataTable
with single record and bind it. Or you can manually populate text boxes.
Another option, and this is interesting, is to load a Dataset
with two tables - 1 combo lookup and another actual data. Establish relationship between them and bind controls. Then you will not have to go to DB every time you change value in combobox
. You will need to refresh data sometimes but everything will be happening on the client.
private void Form4_Load(object sender, EventArgs e)
{
con = new SqlConnection("data source=PC\\SQLEXPRESS;integrated security=true;Initial catalog=MyDB");
BindData1();
}
public void BindData1()
{
DataTable dt = null;
using (SqlConnection con = new SqlConnection("data source=PC\\SQLEXPRESS;integrated security=true;Initial catalog=MyDB"))
{
con.Open();
string strCmd = "select Items from tblbill";
using (SqlCommand cmd = new SqlCommand(strCmd, con))
{
SqlDataAdapter da = new SqlDataAdapter(strCmd, con);
dt = new DataTable("TName");
da.Fill(dt);
}
}
comboBox1.DisplayMember = "field1";
comboBox1.ValueMember = "field2";
comboBox1.DataSource = dt;
textBox1.DataBindings.Add(new Binding("Text", dt, "field3"));
}
}