C#数据库检索

时间:2012-06-21 05:45:38

标签: c#

我再次无法得到我的查询答案。我编写了代码来从数据库中检索数据并通过选择下拉列表将其加载到文本框中。如果我在下拉列表中选择了我的数据,它将无法准确给出答案,而是显示选定的索引0.我的意思是它将显示“-Select-”。文本框中没有任何操作。我已经检查了我的asp页面OnSelectedIndex和AutoPostBack = True。请纠正我..  这是我的代码:

//This is for retrieval of data to dropdown list.
 public void engi()
    {
        DropDownList1.Items.Clear();
        ListItem l = new ListItem();
        l.Text = "-Select-";
        DropDownList1.Items.Add(l);
        DropDownList1.SelectedIndex = 0;
        Conhr.Open();
        SqlCommand cmd = new SqlCommand("select EmployeeName from tbl_EmploeeDetails where Designation like('%Engineer') ", Conhr);
        //SqlCommand cmd=new SqlCommand("select  Sitecode from MRsite where Sitealiasname in (select Componetcode from tbl_Component where Sitecode='" + TextBox1.Text.Trim() + "'");
        SqlDataReader dr;
        dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            ListItem n = new ListItem();
            n.Text = dr["EmployeeName"].ToString().Trim();
            DropDownList1.Items.Add(n);
        }
        dr.Close();
        Conhr.Close();
    }

//This is for retrieval data for text box by selecting DropDown List
 public void des()
    {
        Conhr.Open();
        string s3;
        s3 = "select Designation from tbl_EmploeeDetails where EmployeeName='" + DropDownList1.SelectedItem.Text + "'";
        SqlCommand c3 = new SqlCommand(s3, Conhr);
        SqlDataReader d3;
        d3 = c3.ExecuteReader();
        while (d3.Read())
        {
            TextBox1.Text = d3["Designation"].ToString().Trim();

        }
        d3.Close();
        Conhr.Close();
    }
//Called the method for data retrieval for Textbox

 protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        des();

    }

1 个答案:

答案 0 :(得分:0)

我很高兴你发布了你的代码(好!) - 但我们需要更多信息。

建议:

1)直接查询您的数据库(例如使用MSSQL GUI)。找到有效的“选择”语句。

2)进入调试器。在查询之前打印您的SQL(例如“s3”)。

3)将“好查询”与“失败”查询进行比较。

问题可能就像拼写错误一样简单:

-- Maybe you meant "tbl_EmployeeDetails" here?
s3 = 
  "select Designation from tbl_EmploeeDetails where EmployeeName='" +       
  DropDownList1.SelectedItem.Text + "'";