I have a 3 Layer asp.net c# code. My BL:
public DataTable ddl()
{
base.Link();
string Query = "SELECT [nam], [idZone] FROM [zones] ORDER BY idZone";
DataTable Output_Q = base.SelectDataText(Query);
base.UnLink();
return Output_Q;
}
public void insert()
{
base.Link();
string Query = "INSERT INTO students (fnam, lnam, cod, idZone) VALUES ( '{0}', '{1}', '{2}', {3} )";
Query = string.Format(Query, fnam, lnam, cod, idZone);
base.commanddatatext(Query);
base.UnLink();
My Code:
page_load:
BL_students_new F = new BL_students_new();
DropDownList1.Items.Clear();
DropDownList1.DataSource = F.ddl();
DropDownList1.DataTextField = "nam";
DropDownList1.DataValueField = "idZone";
DropDownList1.DataBind();
btn_insert:
BL_students_new F = new BL_students_new();
F.fnam = TextBox1.Text.Trim();
F.lnam = TextBox2.Text.Trim();
F.cod = TextBox3.Text.Trim();
F.idZone = Convert.ToInt32(DropDownList1.SelectedItem.Value);
F.insert();
it saves every things but dropdownlist value. note that my ddl has text and int value and i need the value to be saved. but it fails. (My DA is OK too.)
From your comment above:
populating ddl is in page_load and inserting is in btn_insert
Page_Load happens before btn_Insert. This happens every time the page is requested, regardless of whether it's a "post back" or not. (After all, the page has to load into a usable state before it can even know the nature of the HTTP request.)
So what's happening is the following:
DropDownList optionsDropDownList options, losing whatever the user selectedA simple way to address this in WebForms is to wrap your DropDownList binding logic in a condition on IsPostBack. Something like this:
// in Page_Load:
if (!IsPostBack)
{
BL_students_new F = new BL_students_new();
DropDownList1.Items.Clear();
DropDownList1.DataSource = F.ddl();
DropDownList1.DataTextField = "nam";
DropDownList1.DataValueField = "idZone";
DropDownList1.DataBind();
}
That way you're only populating the DropDownList when the page is initially requested, not when the user is submitting the form.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With