我的数据记录表包含以下数据:
Name Shiftname operatorname date Plantname Line Machine
Ashwini Shift1(7-3) Operator 1 2011-05-24 Plant 1 Line1 mc1
Deepika Shift2(3-11) Operator 2 2011-05-24 Plant 2 Line3 mc5
Pradeepa Shift2(11-7) Operator 3 2011-05-25 Plant 3 Line5 mc10
Deepika Shift1(7-3) Operator 1 2011-05-25 Plant 1 Line1 mc1
如果用户从日历中选择日期,我提供了2个下拉列表即line和shift以及一个文本框来存储日期,两个文本框用于存储plant和opearatorname的值。
例如,如果用户选择行并从下拉列表和日期从日历中移位,则应在文本框中显示相应的plantname和operatorname for ex 如果用户从下拉列表中选择line1并从dropdownlist中选择shift1并且日期为25/05/2011,那么两个文本框应显示该值为plant1和operator 1
我写的代码如下:
protected void ddlline_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("connection string");
con.Open();
DataTable dt = new DataTable();
SqlCommand sqlCmd = new SqlCommand("SELECT distinct plantname,operatorname FROM datalogging1 WHERE Line='" + ddlline.SelectedItem + "'and date='"+txtdate.Text+"'and shiftname='"+ddlshift.SelectedItem+"'", con);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
//Where ColumnName is the Field from the DB that you want to display
txtplant.Text = dt.Rows[0]["Plantname"].ToString();
txtop.Text = dt.Rows[0]["operatorname"].ToString();
}
}
但它没有显示。
答案 0 :(得分:2)
问题在于您的SQL Query where Clause
,您设置的值是错误的。
它应该是ddlline.SelectedItem.Value
而不是ddlline.SelectedItem
,因为ddlline.SelectedItem
会返回listitem
,但您需要SelectedValue
,这与下拉列表的情况相同{ {1}}
答案 1 :(得分:1)
尝试@Muhammad Akhtar建议,但我也可以看到你没有使用SQL参数,你的代码容易受到SQL注入攻击。这很容易避免,它会使您的嵌入式SQL更漂亮。
SELECT distinct plantname, operatorname
FROM datalogging1
WHERE Line = @Line AND date = @Date AND shiftname = @ShiftName
然后,在执行此语句之前,请添加带值的参数。
sqlCmd.Parameters.AddWithValue("@Line", ddlline.SelectedItem.Value);
// passing the date as text is also a bad idea because it will make your
// date format dependant on culture and language specific settings in both
// the database and application code if you parse the date first and
// pass the value as a DateTime value you eliminate the date format hassle
// that might otherwise occur in the database
sqlCmd.Parameters.AddWithValue("@Date ", txtdate.Text);
sqlCmd.Parameters.AddWithValue("@ShiftName", ddlshift.SelectedItem.Value);
答案 2 :(得分:1)
您必须使用下拉列表文本更改事件来检测用户何时从下拉列表中选择值并实现您的代码以获取该事件中的详细信息