SqlConnection con = new SqlConnection ("****");

con.Open(); string SqlDataPull = ("Select iKodSotr,sFamSotr FROM dbo.tSotrudnik"); SqlCommand cmd = new SqlCommand(SqlDataPull,con); cmd.CommandType = CommandType.Text; SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { SqlDataPull = dr[0].ToString(); cmbMOLFORMreg.Items.Add(SqlDataPull); } 

and then how to get the selected value separately

    1 answer 1

    Either create a class that describes the data you need, or use a DataTable. Then prescribe DisplayMember and ValueMember. Like this (I don’t know what type of field, so I make a string)

     class MyClass { public string iKodSotr {get; set;} public string sFamSotr {get; set;} } ... var data = new List<MyClass>(); while (dr.Read()) { var mc = new MyClass { iKodSotr = dr[0].ToString(), sFamSotr = dr[1].ToString() }; } dr.Close(); cmbMOLFORMreg.DataSource = data; cmbMOLFORMreg.DisplayMember = "iKodSotr"; // То, что будет отображаться пользователю cmbMOLFORMreg.ValueMember = "sFamSotr"; // То, что будет в SelectedValue 

    You can get a copy like this:

     var value = (MyClass)cmbMOLFORMreg.SelectedItem; 

    and work with the whole object. When working in a DataTable, it will look something like this:

     // Получение DataReader'a ... var dt = new DataTable(); dt.Load(dr); dr.Close(); cmbMOLFORMreg.DataSource = dt; cmbMOLFORMreg.DisplayMember = "iKodSotr"; // То, что будет отображаться пользователю cmbMOLFORMreg.ValueMember = "sFamSotr"; // То, что будет в SelectedValue 

    But, I think, using DataTable for such purposes is not very good, but simpler, because no need to describe the class each time. Although I could be wrong.

    • For example, change the request for "Select iKodSotr + sFamSotr FROM dbo.tSotrudnik" - Donil