设置下拉列表';s基于数据库的SelectValue
本文关键字:数据库 SelectValue 下拉列表 设置 | 更新日期: 2023-09-27 17:57:53
我在GridView中有一个DropDownList,我希望所选的值是数据库中特定人员的值
我的下拉列表ASP代码:
<asp:TemplateField HeaderText="Team" SortExpression="Team">
<ItemTemplate>
<asp:DropDownList ID="ddlTeam" runat="server"
DataSourceID="SqlDataSource1" DataTextField="Team"
DataValueField="Team" ondatabound="ddlTeam_DataBound">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:connectionString %>"
SelectCommand="SELECT DISTINCT [Team] FROM [Team_Names]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
我的ddlTeam_OnBound:
protected void ddlTeam_DataBound(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
foreach (ListItem item in ddl.Items)
{
if (item.Text == "valor")
{
item.Text = "Team Valor";
}
else if (item.Text == "mystic")
{
item.Text = "Team Mystic";
}
}
}
UPDATE-无错误,但DDL为空:
DropDownList ddl = new DropDownList();
string query2 = "SELECT team_name FROM sec WHERE job = " + TextBox1.Text;
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(query2, con))
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while(read.Read())
{
ddl.SelectedValue = read["team_name"].ToString();
}
}
con.Close();
}
}
在SqlDataSource
中执行查询中的所有操作,并且在没有必要的情况下不要使用代码隐藏。
<asp:TemplateField HeaderText="Team" SortExpression="Team">
<ItemTemplate>
<asp:DropDownList ID="ddlTeam" runat="server"
DataSourceID="SqlDataSource1" DataTextField="Team_txt"
DataValueField="Team"><%--No need ondatabound="ddlTeam_DataBound"--%>
</asp:DropDownList><%--datasourceId must match --%>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:connectionString %>"
SelectCommand="SELECT DISTINCT [Team],case Team when 'valor' then 'Team Valor' when 'mystic' then 'Team Mystic' else Team end team_txt FROM [Team_Names]"></asp:SqlDataSource>
</ItemTemplate>
</asp:TemplateField>
您没有执行SqlCommand或打开SqlConnection。您应该将输入放入参数中,以防止潜在的SQL注入攻击。
例如:
string teamName = string.Empty;
using (SqlConnection connection = new SqlConnection("your connection string"))
{
connection.Open();
string query = "SELECT DISTINCT team_name FROM sec WHERE job = @job";
SqlParameter param = new SqlParameter
{
ParameterName = "@job",
Value = TextBox1.Text
};
using (SqlCommand command = new SqlCommand(query, connection))
{
command.Parameters.Add(param);
SqlDataReader reader = command.ExecuteReader(CommandBehavior.SingleRow);
if (reader.Read())
{
teamName = reader.GetString(0);
// or
int ord = reader.GetOrdinal("team_name");
teamName = reader.GetString(ord); // Handles nulls and empty strings.
}
}
}
编辑
您还必须正确设置下拉列表。
DropDownList ddl = new DropDownList();
ddl.DataSource = // call your database code - see above
ddl.DataValueField = "ValueProperty";
ddl.DataTextField = "TextProperty";
ddl.DataBind();
ddl.SelectedValue = teamName;