【问题标题】:Search record from database and display value in textbox and drop downlist从数据库中搜索记录并在文本框和下拉列表中显示值
【发布时间】:2020-01-30 22:15:23
【问题描述】:

下面是我的搜索按钮代码。当我搜索学生的记录时,该值显示在文本字段中,但不在下拉列表中。这是什么原因?

SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Final Project\FinalProject\FinalProject\App_Data\Record.mdf;Integrated Security=True;User Instance=True");

try
{
    string query = "select * from student where StdId='" + txtID.Text + "'";
    SqlCommand com = new SqlCommand(query, con);
    SqlDataReader reader = null;

    con.Open();
    reader = com.ExecuteReader();
    if (reader.Read())
    {
        txtfirstname.Text = reader.GetValue(3).ToString();
        txtlastname.Text = reader.GetValue(4).ToString();
        txtfaname.Text = reader.GetValue(5).ToString();
        txtfcellno.Text = reader.GetValue(6).ToString();
        txtfnic.Text = reader.GetValue(7).ToString();
        txthome.Text = reader.GetValue(8).ToString();

        drpclassno.Text = reader.GetValue(9).ToString();
        drpgender.Text = reader.GetValue(10).ToString();
        drpday.Text = reader.GetValue(11).ToString();
        drpmonth.Text = reader.GetValue(12).ToString();
        drpyear.Text = reader.GetValue(13).ToString();
    }
    else
    {
        lblmsg.Text = "Record was not Found...!";
    }

【问题讨论】:

  • 是否有任何异常被抛出?由于您没有告诉我们您的 UI 使用的是什么技术,并且您没有显示任何实际下拉控件的定义,因此很难进一步帮助您。有时不稳定的 UI 行为是由编辑线程不是控件的所有者引起的,即 UI 线程
  • 您的数据库中有多少张表?第 9 到 13 列为空,或者数据在另一个表中,您的查询需要连接多个表。

标签: c# database


【解决方案1】:

这里使用的技术好像是ASP.NET,因为Windows Forms/WPF中的DropDownList叫做ComboBox

您分配不在列表源中的值。

要将值分配给DropDownList,它必须在其DataSource 中:

drpclassno.DataSource = new List<string> { "1", "2", "3" };
drpclassno.DataBind();
drpclassno.Text = "3"; // Works, because its in the Source

drpclassno.DataSource = new List<string> { "1", "2", "3" };
drpclassno.DataBind();
drpclassno.Text = "4"; // Does not work

您也可以使用SelectedValue 属性而不是Text 来使您的意图更清晰。

【讨论】:

    猜你喜欢
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多