0

我想将数据库中五个标签的值分配给列表框中选择的值。
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)
    {
    }
}
4

1 回答 1

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);

            }
于 2013-11-11T09:25:12.283 回答