Reputation: 261
I have to display values into text box while selecting drop down list. I have use data set to get values from db. The code is given below. Give me a proper solution. Thank you.
Code:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet1TableAdapters.TextBoxTableTableAdapter tx;
tx = new DataSet1TableAdapters.TextBoxTableTableAdapter();
DataTable dt = new DataTable();
dt = tx.GetstudData(int.Parse(DropDownList1.SelectedValue));
foreach (DataRow row in dt.Rows)
{
TextBox1.Text = (row["FirstName"]); // error shown here
TextBox2.Text = (row["SecondName"]); // error shown here
}
}
The dt contains First Name and Last Name values. While selecting student ID the appropriate value shoud be shown in text box1 and textbox 2.
Sql query:
SELECT FirstName, SecondName FROM TextBoxTable WHERE (Id = @Id)
Source:
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</div>
Data base:
Upvotes: 0
Views: 21697
Reputation: 136
studentId is unique. DownDropList Contains Studentid. one student has one Name
if(DropDownList1.SelectedValue !="" && dt.Rows.Count()>0)
{
txtFirstname.Text= String.IsNullOrWhiteSpace(dt.Rows[0]["FirstName"]) ? "" : dt.Rows[0]["FirstName"];
txtlastName.Text= String.IsNullOrWhiteSpace(dt.Rows[0]["LastName"]) ? "" : dt.Rows[0]["LastName"];
}
else
{
TextBox1.Text="";
TextBox2.Text="";
}
Upvotes: 1
Reputation: 195
Change your code to:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
DataSet1TableAdapters.TextBoxTableTableAdapter tx;
tx = new DataSet1TableAdapters.TextBoxTableTableAdapter();
DataTable dt = new DataTable();
dt = tx.GetstudData(int.Parse(DropDownList1.SelectedValue));
foreach (DataRow row in dt.Rows)
{
TextBox1.Text = (row["FirstName"].ToString());
TextBox2.Text = (row["SecondName"].ToString());
}
}
The names of the text boxes are different from the ones you have in the asp file. C# is a case sensitive language.
EDIT: You have to convert it. A simple .ToString() should do it. Try not to change the complete subject of the topic also. You should have open a new question...because this breaks all the correct answers.
Upvotes: 3
Reputation: 583
You may want to do :
foreach (DataRow row in dt.Rows)
{
TextBox1.Text = (row["FirstName"]);
TextBox2.Text = (row["SecondName"]);
}
Upvotes: 3