Dropdownlist how to save selected value to ViewState? - c#

Dropdownlist how to save selected value to ViewState ?
I have a dropdownlist that when changed will save the new value into a ViewState variable, so that after a postback, the dropdownlist will retrieve it's selected value from ViewState if previously set.
But I can't store the selected value in DropDownList1_SelectedIndexChanged to ViewState because when reload page (after update database with sql query update) in DropDownList I don't have any selected value.
Can you please help me figure out the problem?
Thanks in advance.
My code below.
<asp:DropDownList ID="ddl1" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ddl1_SelectedIndexChanged"
EnableViewState="true" ViewStateMode="Enabled">
<asp:ListItem Value="" Text="[Selected]"></asp:ListItem>
<asp:ListItem Value="" Text="------"></asp:ListItem>
<asp:ListItem Value="1" Text="A"> </asp:ListItem>
<asp:ListItem Value="2" Text="B"> </asp:ListItem>
<asp:ListItem Value="3" Text="C"> </asp:ListItem>
<asp:ListItem Value="4" Text="D"> </asp:ListItem>
<asp:ListItem Value="" Text="------"></asp:ListItem>
</asp:DropDownList>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
if (ViewState["List1_Value"] != null)
{
ddl1.SelectedValue = ViewState["List1_Value"].ToString();
}
}
}
protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
{
BindData();
ViewState["List1_Value"] = ddl1.SelectedValue.ToString();
}
private void SqlUpdate()
{
sql = String.Format(#" UPDATE ..... ";
using (OdbcConnection cn =
new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
{
using (OdbcCommand cmd = new OdbcCommand(sql, cn))
{
cmd.Connection.Open();
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg", "alert('Ok.');window.location='default.aspx';", true);
}
}
}

You have AutoPostBack enabled, so every time the selection change it posts back to your Page_Load. You are only filling out the value when it is not a postback, so this will never occur.
Try moving the code to set the value outside of the if (!Page.IsPostBack) block. Maybe something like so:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
if (ViewState["List1_Value"] != null)
{
ddl1.SelectedValue = ViewState["List1_Value"].ToString();
}
}

when reload page (after update database with sql query update) in DropDownList I don't have any selected value
Presumably you're "reloading" in one of two ways:
1. Causing a Post-Back
This won't work in your case because you're not using the value in a post-back:
if (!Page.IsPostBack)
{
BindData();
if (ViewState["List1_Value"] != null)
{
ddl1.SelectedValue = ViewState["List1_Value"].ToString();
}
}
If you want to bind the selected value in a post-back then you need to move that code outside of that conditional:
if (!Page.IsPostBack)
{
BindData();
}
if (ViewState["List1_Value"] != null)
{
ddl1.SelectedValue = ViewState["List1_Value"].ToString();
}
2. Making a New Request
If you're manually "reloading" the page by simply re-requesting the page from the browser's address bar, then the ViewState is going to be empty. ViewState is part of the form values in a POST request, but loading a page from the address bar issues a GET request with no values. So the ViewState will be empty.

Remove BindData() from your SelectedIndexChanged method:
protected void ddl1_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState["List1_Value"] = ddl1.SelectedValue.ToString();
}
And as others have mentioned, you attempt to set ddl1.SelectedValue inside a condition that only runs in NOT postback, which means it will never capture the selected value on postback. So you will also want to address that by moving it outside the !Page.IsPostBack condition.

What you're doing is a postback from Javascript, in this case the ViewState is deleted as it is as if it were a new request.
In this case the only thing is to store it in session or send as a parameter to the page.
At last after update database simply binding a GridView it's easy !:
cmd.Connection.Open();
cmd.ExecuteNonQuery();
Page.ClientScript.RegisterStartupScript(this.GetType(), "Msg", "alert('Ok.');", true);
BindData();

Related

How to make a connection to a database using DropDownList

So I want to have a DDL (SELECT name FROM sys.databases (nolock)) that returns a value once selected (displayed in gridview possibly).
The problem that I have is that the query needs to make a connection to different databases depending on what the user selects from the DDL and return a value that is displayed in gridview. I want something like the below query:
How could I accomplish this?
use ([name]=#name) select sum(t.table1.column1) as Total from database inner join database2 on db1.table1.id= ([name]=#name).table2.id where([appname]=#appname) and Date <= GetDate()AND YEAR(Date) = year(GetDate())
I got this so far (not sure if this is the best method.) This is my code behind, how do I display the result using gridview that is dependent on DDL?
protected void DropDownList2_SelectedIndexChanged(object sender, EventArgs e)
{
{
if (DropDownList2.SelectedValue == "test1")
{
SqlDataSource3.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["test1ConnectionString"].ConnectionString;
{
SqlDataSource3.SelectCommandType = SqlDataSourceCommandType.Text;
SqlDataSource3.SelectCommand = "select top 10 * from table1 (nolock)";
}
}
else if (DropDownList2.SelectedValue == "test2")
{
SqlDataSource4.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["test2ConnectionString"].ConnectionString;
{
SqlDataSource4.SelectCommandType = SqlDataSourceCommandType.Text;
SqlDataSource4.SelectCommand = "select top 1 * from table1 (nolock)";
}
}
And below is my aspx code for the DDL.
<asp:DropDownList ID="DropDownList2" runat="server" AutoPostBack="True" OnSelectedIndexChanged="DropDownList2_SelectedIndexChanged">
<asp:ListItem>test1</asp:ListItem>
<asp:ListItem>test2</asp:ListItem>
</asp:DropDownList>
From what I understand you want to run different SQL when a user selects an item from the DropDownList. Anyway, you should put your code in the SelectedIndexChanged event of the control. As an example, your markup might look something like this:
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
And in your code-behind:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
// call your sql
}
Edit
I've included a links to get your started. They show some code with the SelectedIndexChanged event.
http://www.devasp.net/net/articles/display/1294.html
http://www.c-sharpcorner.com/UploadFile/092589/working-with-dropdownlist-slectedindexchanged-event/

Setting SelectedValue of DDL on PageLoad using value saved in Session Variable

I'm trying to set the selected value of a DropDownList on Page_Load using a value that is saved into a Session variable. The DropDownList is already populated and the value is stored along with other info in a session. I'm creating an edit entry page and want to have all of the fields already populated with the info from the Session.
What I've done is populate TextBox with the Session Variables, but for the Advisors section I need the User to enter a number instead of a name. So I need to use a DropDownList to make sure that information is entered accurately. I've looked into methods of databinding, databound, using a data source, etc but it seemed like all of those DropDownLists were generated dynamically. Any help would be much appreciated.
My .aspx Code:
<asp:TextBox runat="server" ID="fname" MaxLength="100"></asp:TextBox>
<asp:DropDownList ID="advisors" runat="server">
<asp:ListItem Value="">Select Advisor</asp:ListItem>
<asp:ListItem Value="2">Joe Schmo</asp:ListItem>
</asp:DropDownList>
Code Behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fname.Text = Session["fname"].ToString();
lname.Text = Session["lname"].ToString();
sex.Text = Session["sex"].ToString();
sid.Text = Session["sid"].ToString();
email.Text = Session["email"].ToString();
phone.Text = Session["phone"].ToString();
advisors.SelectedValue = Session["advisor"].ToString();
}
}
UPDATE:
So I'm dumb. The Session variable was storing the name "Joe Schmo" not the Value "2". The below code worked for me.
foreach (ListItem listItem in advisors.Items)
{
listItem.Selected = listItem.Text.Equals(Session["advisor"].ToString());
}
try this
foreach (ListItem listItem in advisors.Items)
{
if(listItem.Text.Equals(Session["advisor"].ToString())
DropDownList1.Items.FindByValue(Session["advisor"].ToString()).Selected = true;
}

Dropdownlist SelectedIndexChanged firing on every postback

I am dynamically adding a custom user control to an update panel. My user control contains two dropdownlists and a textbox. When a control outside of the update panel triggers a postsback, I am re-adding the user control to the update panel.
The problem is...on postback when I re-add the user controls, it's firing the "SelectedIndexChanged" event of the dropdownlists inside the user control. Even if the selectedindex did not change since the last postback.
Any ideas?
I can post the code if necessary, but there's quite a bit in this particular scenario.
Thanks in advance!
EDIT...CODE ADDED BELOW
*.ASCX
<asp:DropDownList ID="ddlColumns" OnSelectedIndexChanged="ddlColumns_SelectedChanged" AppendDataBoundItems="true" AutoPostBack="true" runat="server">
*.ASCX.CS
List<dataColumnSpecs> dataColumns = new List<dataColumnSpecs>();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fillDDLColumns();
}
}
public void fillDataColumnsList()
{
dataColumns.Clear();
//COMMON GETDATATABLE RETURNS A DATA TABLE POPULATED WITH THE RESULTS FROM THE STORED PROC COMMAND
DataTable dt = common.getDataTable(storedProcs.SELECT_COLUMNS, new List<SqlParameter>());
foreach (DataRow dr in dt.Rows)
{
dataColumns.Add(new dataColumnSpecs(dr["columnName"].ToString(), dr["friendlyName"].ToString(), dr["dataType"].ToString(), (int)dr["dataSize"]));
}
}
public void fillDDLColumns()
{
fillDataColumnsList();
ddlColumns.Items.Clear();
foreach (dataColumnSpecs dcs in dataColumns)
{
ListItem li = new ListItem();
li.Text = dcs.friendlyName;
li.Value = dcs.columnName;
ddlColumns.Items.Add(li);
}
ddlColumns.Items.Insert(0, new ListItem(" -SELECT A COLUMN- ", ""));
ddlColumns.DataBind();
}
protected void ddlColumns_SelectedChanged(object sender, EventArgs e)
{
//THIS CODE IS BEING FIRED WHEN A BUTTON ON THE PARENT *.ASPX IS CLICKED
}
*.ASPX
<asp:UpdatePanel ID="upControls" runat="server">
<ContentTemplate>
<asp:Button ID="btnAddControl" runat="server" Text="+" OnClick="btnAddControl_Click" />
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="btnGo" runat="server" Text="Go" OnClick="btnGo_Click" ValidationGroup="vgGo" />
<asp:GridView...
*.ASPX.CS
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
uc_Counter = 0;
addControl();
gridview_DataBind();
}
else
{
reloadControls();
}
}
protected void btnGo_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//THIS BUTTON CLICK IS WHAT'S TRIGGERING THE
//SELECTEDINDEXCHANGED EVENT TO FIRE ON MY *.ASCX
gridview_DataBind();
}
}
private void reloadControls()
{
int count = this.uc_Counter;
for (int i = 0; i < count; i++)
{
Control myUserControl = Page.LoadControl("~/Controls/myUserControl.ascx");
myUserControl.ID = "scID_" + i;
upControls.ContentTemplateContainer.Controls.AddAt(i, myUserControl);
((customUserControl)myUserControl).fillDDLColumns();
}
}
private void addControl()
{
Control myUserControl = Page.LoadControl("~/Controls/myUserControl.ascx");
myUserControl.ID = "scID_" + uc_Counter.ToString();
upControls.ContentTemplateContainer.Controls.AddAt(upControls.ContentTemplateContainer.Controls.IndexOf(btnAddControl), myUserControl);
//((customUserControl)myUserControl).fillDDLColumns();
this.uc_Counter++;
}
protected int uc_Counter
{
get { return (int)ViewState["uc_Counter"]; }
set { ViewState["uc_Counter"] = value; }
}
Even though this is already answered I want to put an answer here since I've recently tangled with this problem and I couldn't find an answer anywhere that helped me but I did find a solution after a lot of digging into the code.
For me, the reason why this was happening was due to someone overwriting PageStatePersister to change how the viewstate hidden field is rendered. Why do that? I found my answer here.
One of the greatest problems when trying to optimize an ASP.NET page to be more search engine friendly is the view state hidden field. Most search engines give more score to the content of the firsts[sic] thousands of bytes of the document so if your first 2 KB are view state junk your pages are penalized. So the goal here is to move the view state data as down as possible.
What the code I encountered did was blank out the __VIEWSTATE hidden fields and create a view_state hidden field towards the bottom of the page. The problem with this is that it totally mucked up the viewstate and I was getting dropdownlists reported as being changed when they weren't, as well as having all dropdownlists going through the same handler on submit. It was a mess. My solution was to turn off this custom persister on this page only so I wouldn't have to compensate for all this weirdness.
protected override PageStatePersister PageStatePersister
{
get
{
if (LoginRedirectUrl == "/the_page_in_question.aspx")
{
return new HiddenFieldPageStatePersister(Page);
}
return new CustomPageStatePersister(this);
}
}
This allowed me to have my proper viewstate for the page I needed it on but kept the SEO code for the rest of the site. Hope this helps someone.
I found my answer in this post .net DropDownList gets cleared after postback
I changed my counter that I was storing in the viewstate to a session variable.
Then I moved my reloadControls() function from the Page_Load of the *.ASPX to the Page_Init.
The key was dynamically adding my user control in the Page_Init so it would be a member of the page before the Viewstate was applied to controls on the page.

HtmlInputCheckBox in Repeater always not checked

i'm using a HtmlInputCheckBox in a repeater by adding
<input id="CheckBox1" type="checkbox" runat="server" value='<%# Eval ("userid") %>' />
to repeater->ItemTemplate->table->tr->td and in the server side i'm using
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < UserRepeater.Items.Count; i++)
{
var chkBox = UserRepeater.Items[i].FindControl("CheckBox1") as HtmlInputCheckBox;
if (chkBox != null && chkBox.Checked)
{
//
}
}
}
i'm not programatically setting any checkbox to set - i'm checking them on the web page during test.
my var checkbox is always inchecked {Value = "1,2,3,4" Checked = false}, thx for helping me with that.
How are you populating your repeater - if you are doing it in page_load make sure it is protected for postbacks:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// populate your data
}
}
EDIT
This is assuming you are working with viewstate on - which is the case by default.
This may be to do with when you bind your repeater. If you are binding on Page_Load, the check boxes will be created after viewstate and post variables have been restored, so the value won't be on your checkboxes.
If possible, move the data bind to Page_Init; as this happens before viewstate/post values are restored your checkboxes will get the right values assigned. If you can't bind on Page_Init, then #Aristos's answer will do.

page strange behavior

I face so strange action in my page.
I have a radio button list, according to the selection i execute specific code.
The problem is:
for example when i select option 2 then i select back option 1.
the page maintains the state(all the drop down lists maintain their previous selections) and i need to click the link one more time to force the page to enter this condition:
if (!Page.IsPostBack)
{
BindCamp(0);
BindCamp(1);
}
my aspx :
<asp:RadioButtonList ID="rbl" runat="server"
OnSelectedIndexChanged="rbl_SelectedIndexChanged"
RepeatDirection="Horizontal" Width="200px" AutoPostBack="True">
<asp:ListItem Value="0" Selected="True">view data</asp:ListItem>
<asp:ListItem Value="1">view report</asp:ListItem>
</asp:RadioButtonList>
My code:
protected void rbl_SelectedIndexChanged(object sender, EventArgs e)
{
if (rbl.SelectedItem.Value == "0")
{
pnl_view.Visible = true;
pnl_stat.Visible = false;
pnl_rep.Visible = false;
}
else
{
pnl_view.Visible = false;
pnl_all.Visible = false;
pnl_Dean.Visible = false;
pnl_research.Visible = false;
pnl_stat.Visible = true;
}
}
Per your comments, DLL's will always retain their values unless you manually set the selection, you set EnableViewState="false" (which disabled all viewstate then). So I think you may need code that does:
ddl.SelectedIndex = 0; // or -1 depending on whether you want an item selected
Upon clicking the next radio button.

Categories

Resources