根据列表框值将值分配给标签数据库

时间:2013-11-11 09:18:56

标签: c# .net sql listbox

我想将数据库中五个标签的值分配给列表框中选择的值 db查询返回具有多个记录的单个列。 请帮忙。
我正在使用C#2010和MS SQL。

我目前的代码是:

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    try
    {
        String c1, c2;
        c1 = "NULL";
        MessageBox.Show("LB index :"+listBox1.SelectedIndex.ToString());
        //p = listBox1.SelectedItem.ToString();
        SqlConnection con = new SqlConnection();
        con.ConnectionString = "Data Source=localhost;Initial Catalog=eVoting;Integrated Security=True;Pooling=False";
        con.Open();
        MessageBox.Show("List bOx sect  :"+listBox1.SelectedValue.ToString());
        SqlCommand cmd = new SqlCommand("select Firstname from candidates where position ='" + listBox1.SelectedValue.ToString() + "'", con);
        int index = 0;
        SqlDataReader reader = cmd.ExecuteReader();
        while(reader.Read())
        {
            if (index == 0)
            {
                c1 = reader[index].ToString();
                radioButton1.Text = c1;
            }
            if (index == 1)
            {
                c1 = reader[index].ToString();
                radioButton2.Text = c1;
            }
            if (index == 2)
            {
                c1 = reader[index].ToString();
                radioButton3.Text = c1;
            }
            if (index == 3)
            {
                c1 = reader[index].ToString();
                radioButton4.Text = c1;
            }
            if (index == 4)
            {
                c1 = reader[index].ToString();
                radioButton4.Text = c1;
            }
            if (index == 5)
            {
                c1 = reader[index].ToString();
                radioButton5.Text = c1;
            }
            MessageBox.Show("c1  :" + c1);
            index++;
        }

    }
    catch (Exception E)
    {
    }
}

1 个答案:

答案 0 :(得分:0)

制作

DataTable dt=new DataTable();
        dt.Load(reader);
        for (int i = 0; i < dt.Rows.Count;i++ )
        {
            {
                if (i == 0)
                {
                    c1 = dt.Rows[i]["Firstname "].ToString();
                    radioButton1.Text = c1;
                }
                if (index == 1)
                {
                    c1 = dt.Rows[i]["Firstname "].ToString();
                    radioButton2.Text = c1;
                }
                ..
                MessageBox.Show("c1  :" + c1);

            }