Hi
i'm trying to insert a int value (id) into a table of sql server. That value is the part before the space of the selectedvalue of a dropdownlist. Because id is defined as internal, i thought it would keep its value in all events, but obviously doesn't. Why and how to fix that (possible with session variable)? I put the property CausesValidation="false" of the button but still same problem.
Thanks
V
internal int id;
protected void dd2_SelectedIndexChanged(object sender, EventArgs e)
{
string sel = dd2.SelectedValue;
int pos = sel.IndexOf(" ");
id = Int32.Parse(sel.Substring(0, pos));
}
protected void Button1_Click(object sender, EventArgs e)
{
Label2.Text = id.ToString();// this shows 0
mConnection.Open();
sql = "insert into number (idll) values (@idll)";
comd = new SqlCommand(sql, mConnection);
comd.Parameters.AddWithValue("@idll", Convert.ToInt32(id));
comd.ExecuteNonQuery();
mConnection.Close();
}
Sachin SinghPosted Jun 25, 2022, 11:33 AM
In asp.net or any other client-server-based technology, which is based on HTTP, each request is a fresh request where after processing the request all the control's values and variables defined in the page become null.
This is how client-server architecture works.
In desktop app we make internal requests unless web API is used, so states are maintained. But in Web apps we need to explicitly maintain the state, using any state management techniques like Session variable, Application variable, ViewState (In asp.net web forms), (ViewBag, ViewData, TempData (In Asp.Net MVC).
also, your Selected Index changed event is doing a full post back, making the value null, similar to any button click. You can maintain the value by not setting the PostBack property to true for dropdown list.
Valerie MeunierPosted Jun 25, 2022, 11:48 AM
Valerie MeunierPosted Jun 25, 2022, 11:05 AM
Sachin SinghPosted Jun 25, 2022, 10:05 AM