【发布时间】:2013-12-03 17:13:53
【问题描述】:
我有一个链接到 SQL 数据库的 DropDownList。它目前显示客户列表。我正在尝试这样做,以便一旦选择了客户,就会自动填充多个文本框(例如地址、城市等)。我能够自动填充“公司名称”文本框,因为该值是选定的值,但我不知道如何使用行中的其余数据填充其他文本框。我最好怎么做?
在 .aspx 中:
<asp:DropDownList ID="DropDownList1" runat="server" ></asp:DropDownList>
C#:
DataTable customers = new DataTable();
...
SqlDataAdapter adapter = new SqlDataAdapter("SELECT CustomerName FROM Customers.dbo.Customer", connection);
adapter.Fill(customers);
DropDownList1.DataSource = customers;
DropDownList1.DataTextField = "CustomerName";
DropDownList1.DataValueField = "CustomerName";
DropDownList1.DataBind();
编辑:感谢卡尔的帮助。如果您有类似的问题,请遵循他的建议。另外,请确保更改下拉列表,使其看起来像:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" onselectedindexchanged="CompanyChanged"></asp:DropDownList>
EDIT2:对于那些有同样问题的人。这是我的代码:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadOptions();
}
}
protected void LoadOptions()
{
DataTable customers = new DataTable();
SqlConnection connection = new SqlConnection(INSERT YOUR CONNECTION STRING HERE);
using (connection)
{
SqlDataAdapter adapter = new SqlDataAdapter("SELECT Column1 FROM Table", connection);
adapter.Fill(customers);
DropDownListID.DataSource = customers;
companyselect.DataTextField = "Column1";
companyselect.DataValueField = "Column1";
companyselect.DataBind();
}
}
protected void SelectionChanged(object sender, EventArgs e)
{
string selected= DropDownListID.SelectedItem.Value;
SqlConnection connection = new SqlConnection(YOUR CONNECTION STRING);
using (connection)
{
SqlCommand command = new SqlCommand("SELECT * FROM Table WHERE Column1= @Column1", connection);
command.Parameters.AddWithValue("@Column1", selected);
command.CommandType = CommandType.Text;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
using (reader)
{
if (reader.HasRows)
{
reader.Read();
//add as many as needed to fill your textboxes
TextBox1.Text = reader.GetString(1);
TextBox2.Text = reader.GetString(2);
TextBox3.Text = reader.GetString(3);
}
else { }
}
}
}
这就是我的下拉列表的样子:
<asp:DropDownList ID="DropDownListID" runat="server" AutoPostBack="true" onselectedindexchanged="SelectionChanged"></asp:DropDownList>
【问题讨论】:
-
发布您的代码是很好的第一步。
-
@KarlAnderson 我添加了我的代码。希望这会有所帮助。
-
恕我直言,最好的方法是像您正在做的那样对数据库进行一次调用。一旦选择了一个。再打一个电话以获取详细信息。这样,如果您有 1000 个客户,您就不会拉下 10,000 行(10 个字段)
-
数据库中有标识列吗?
-
@logixologist 是的,数据库中的每个客户都有一个 ID。选择选项后,如何再次调用数据库以获取其余详细信息?