DropDownList没有填充文本框。为什么? [英] DropDownList not populating Textbox. Why?
问题描述
我有一个代码来填充文本框,具体取决于ddl值。为什么我的代码不起作用?我做错了什么?
<前lang =c#> 受保护 void DropDownListLongName_SelectedIndexChanged( object sender,EventArgs e)
{
SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings [ HotConnectionString ] .ConnectionString);
con2.Open();
SqlCommand scmd = new SqlCommand( 从Table99中选择User_ID,LongName,其中LongName =' + DropDownListLongName + ',con2);
SqlDataReader dr = scmd.ExecuteReader();
if (dr.Read())
{
TextBoxUser_ID.Text = dr [< span class =code-string> User_ID]。ToString();
}
dr.Close();
con2.Close();
}
}
}
首先修复 SQL注入 [ ^ ]漏洞。
那将告诉您,您正在尝试将DropDownList
控件传递给查询,而不是传递其选定的值。
此外,您应该使用块在中包装所有实现
IDisposable
的对象。
要从查询中检索单个值,就不需要DataReader
- 只需调用ExecuteScalar
。
protected void DropDownListLongName_SelectedIndexChanged( object sender,EventArgs e)
{
使用(SqlConnection con2 = new SqlConnection( System.Configuration.ConfigurationManager.ConnectionStrings [ HotConnectionString]。ConnectionString))
使用(SqlCommand scmd = new SqlCommand( < span class =code-string>从Table99中选择User_ID,其中LongName = @LongName,con2))
{
scmd.Parameters.AddWithValue( @ LongName,DropDownListLongName.SelectedValue);
con2.Open();
TextBoxUser_ID.Text = Convert.ToString(smcd.ExecuteScalar());
}
}
I have a code to populate a textbox depending on the ddl value. Why is my code not working? What did I do wrong?
protected void DropDownListLongName_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["HotConnectionString"].ConnectionString);
con2.Open();
SqlCommand scmd = new SqlCommand("Select User_ID, LongName from Table99 where LongName = '" + DropDownListLongName + "'", con2);
SqlDataReader dr = scmd.ExecuteReader();
if (dr.Read())
{
TextBoxUser_ID.Text = dr["User_ID"].ToString();
}
dr.Close();
con2.Close();
}
}
}
Start by fixing the SQL Injection[^] vulnerability in your code.
That will then tell you that you're trying to pass theDropDownList
control to the query, instead of passing its selected value.
Also, you should wrap all objects that implementIDisposable
in ausing
block.
And to retrieve a single value from the query, there's no need for aDataReader
- just callExecuteScalar
.
protected void DropDownListLongName_SelectedIndexChanged(object sender, EventArgs e) { using (SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["HotConnectionString"].ConnectionString)) using (SqlCommand scmd = new SqlCommand("Select User_ID from Table99 where LongName = @LongName", con2)) { scmd.Parameters.AddWithValue("@LongName", DropDownListLongName.SelectedValue); con2.Open(); TextBoxUser_ID.Text = Convert.ToString(smcd.ExecuteScalar()); } }
这篇关于DropDownList没有填充文本框。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!