C# Fill combo box from SQL DataTable

后端 未结 3 1039
梦谈多话
梦谈多话 2020-12-21 20:56
DataTable _dt = new DataTable();

using (SqlConnection _cs = new SqlConnection(\"Data Source=COMNAME; Initial Catalog=DATABASE; Integrated Security=True\"))
{
    st         


        
3条回答
  •  悲哀的现实
    2020-12-21 21:26

    I'm not yet sure what is the exact error in your code, but if you're ok with not using DataTable, you can do it this way:

    using (SqlConnection sqlConnection = new SqlConnection("connstring"))
    {
        SqlCommand sqlCmd = new SqlCommand("SELECT * FROM Doctor", sqlConnection);
        sqlConnection.Open();
        SqlDataReader sqlReader = sqlCmd.ExecuteReader();
    
        while (sqlReader.Read())
        {
            cbDoctor.Items.Add(sqlReader["name"].ToString());
        }
    
        sqlReader.Close();
    }
    

    For more information take a look at SqlDataReader reference on MSDN.

    In orer to find the issue in the original code you posted, please provide information in which line you get the exception (or is it an error that prevents application from compiling?) and what is its whole message.

提交回复
热议问题