I have a DropDownList that is linked to a SQL database. It currently shows a list of customers. I am trying to make it so that once a customer is selected, multiple textboxes are automatically filled (such as address, city, etc). I am able to automatically fill the "company name" textbox as the value is the one selected, but I do not know how to fill the other textboxes using the rest of the data in the row. How would I best go about doing this?
in .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();
EDIT: Thanks Karl for your help. Follow his advice if you have a similar issue. Also, make sure to change the dropdownlist so it looks like:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="true" onselectedindexchanged="CompanyChanged"></asp:DropDownList>
EDIT2: For those that are having the same problem.. Here is my code:
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 { }
}
}
}
And this is what my dropdownlist looks like:
<asp:DropDownList ID="DropDownListID" runat="server" AutoPostBack="true" onselectedindexchanged="SelectionChanged"></asp:DropDownList>