3Layer C # asp.net: insert dropdown of selected text and value
I have ap.net C # 3 Layer 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 retains everything except the dropdownlist value. note that my ddl is text and int and I need to store the value. but it fails. (My DA is fine too.)
source to share
From your comment above:
popping ddl is in page_load and insert is in btn_insert
Page_Load
happens before btn_Insert
. This happens every time a page is requested , regardless of whether it is "post back" or not. (After all, the page must load into a usable state before it can even know the nature of the HTTP request.)
So what's going on:
- Bind options
DropDownList
- Show page to user
- User selects a parameter and submits
- Rebind parameters
DropDownList
, losing everything that was selected by the user - Insert into database
An easy way to solve this problem in WebForms is to bundle your binding logic DropDownList
into state IsPostBack
. Something like that:
// 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();
}
This way you only fill DropDownList
out when the page is initially requested, not when the user submits the form.
source to share