DropDownList SelectedValue doesn't Change - c#

In my page when I call searchBtn_Click the selectedvalue will be carried into the variable ind only if the selection hasnt changed. So if a User selects Automotive, then clicks the search button, and then they change the selection to Government, it will refresh the page and display Automotive, am I missing something in the postback or doing something wrong here?
protected void Page_Load(object sender, EventArgs e)
{
string industry = "";
if (Request.QueryString["ind"] != null)
{
industry = Request.QueryString["ind"].ToString();
if (industry != "")
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
}
}
protected void searchBtn_Click(object sender, EventArgs e)
{
string ind = IndustryDropDownList.SelectedValue;
Response.Redirect("Default.aspx?ind=" + ind);
}

Simply replace your code with this code
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
string industry = "";
if (Request.QueryString["ind"] != null)
{
industry = Request.QueryString["ind"].ToString();
if (industry != "")
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
}
}
}

You don't need to use Redirect and QueryString.
Use SelectedValue at Page_PreRender (In your sample clear Page_Load completely).

you better try this in search button click
but remember your dropdowndlist's value-member==display-member to do this.. i had the same problem and this is how i solved it.
string ind = IndustryDropDownList.Text.Tostring().Trim();
Response.Redirect("Default.aspx?ind=" + ind);
i knw this is not the best way but it did work for me..

You're not leveraging the ViewState of asp.net forms (good mentality for MVC 3 though). But since you are using asp.net, you should change your code to this:
The logic in your page load is not necessary, unless you want the user to set the industry as the enter the page. Since I assumed you do, I left some logic in there. It checks for postback because it doesn't need to execute after the initial page load.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack() && Request.QueryString["ind"] != null)
{
SetIndustry(Request.QueryString["ind"].ToString());
}
}
protected void SetIndustry(String industry)
{
indLabel.Text = "Industry: " + industry;
IndustryDropDownList.SelectedValue = industry;
}
You don't have to redirect the page, since Page_Load will be called every time the page posts back. With .NET, your controls remember their last values automatically.
protected void searchBtn_Click(object sender, EventArgs e)
{
SetIndustry(IndustryDropDownList.SelectedValue);
}

Related

Clear content from fields after save .net c#

I have aspx form with textboxes and gridview.
When i insert data to textbox it's shows on the gridview after clicking "Save".
I need to clear the content of fieds after i click on "Save".
I tried alot of things and searched in google but nothing works.
I am new at .net.. Can someone help please?
This is my save button fuction:
protected void btnSave_Click(object sender, EventArgs e)
{
Context1.sp_CreateUserTest(txtName.Text, txtEmail.Text, txtMobile.Text, DateTime.Parse(txtBirthdate.Text));
grdvUsers.DataBind();
}
This is my pageLoad:
protected void Page_Load(object sender, EventArgs e)
{
grdvUsers.DataSource = Context1.sp_GetAllUserTest(); // select all users into gridview. datasorce = the data we want to dispaly.
grdvUsers.DataBind();
}
Simply make a method for clearing the controls that you want to clear:
private void ClearControls()
{
txtName.Text =""; // resetting textbox
txtEmail.Tex="";
txtMobile.Text ="";
ddlSomeDropDown.SelectedIndex = -1; // reset dropdown
somecheckBox.Checked = false; // reset checkbox
someRadio.Checked = false; // reset radio
..................
.................
// more controls here
}
and call it after saving :
protected void btnSave_Click(object sender, EventArgs e)
{
Context1.sp_CreateUserTest(txtName.Text, txtEmail.Text, txtMobile.Text, DateTime.Parse(txtBirthdate.Text));
grdvUsers.DataBind();
ClearControls();
}
Just assign text fields a empty string.
protected void btnSave_Click(object sender, EventArgs e)
{
Context1.sp_CreateUserTest(txtName.Text, txtEmail.Text, txtMobile.Text, DateTime.Parse(txtBirthdate.Text));
txtName.Text = String.Empty;
txtEmail.Text= String.Empty;
txtMobile.Text= String.Empty;
txtBirthdate.Text= String.Empty;
grdvUsers.DataBind();
}
You can also do this.
You can clear date and datepicker with DatetimePicker1.Clear(); or with the provided ID

How to set website theme to all webpages using a drop down list?

I am trying to use a drop down list on my homepage to select and set the theme for all webpages. It sets it for the homepage but when I go to any other page it has no theme. This is my code for my homepage:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string selectedTheme = Page.Theme;
HttpCookie userSelectedTheme =
Request.Cookies.Get("UserSelectedTheme");
if (userSelectedTheme != null)
{
selectedTheme = userSelectedTheme.Value;
}
if (!string.IsNullOrEmpty(selectedTheme) &&
ddlSetTheme.Items.FindByValue(selectedTheme) != null)
{
ddlSetTheme.Items.FindByValue(selectedTheme).Selected =
true;
}
}
}
protected void ddlSetTheme_SelectedIndexChanged(object sender, EventArgs e)
{
HttpCookie userSelectedTheme = new
HttpCookie("UserSelectedTheme");
userSelectedTheme.Expires = DateTime.Now.AddMonths(6);
userSelectedTheme.Value = ddlSetTheme.SelectedValue;
Response.Cookies.Add(userSelectedTheme);
Response.Redirect(Request.Url.ToString());
}
private void Page_PreInit(object sender, EventArgs e)
{
HttpCookie setTheme = Request.Cookies.Get("UserSelectedTheme");
if (setTheme != null)
{
Page.Theme = setTheme.Value;
}
}
I am thinking that the code I have is only sufficient to apply the theme to one page, so how do I apply it to all pages?
By default, your HttpCookie's scope is the page you're on.
If you want it to be the entire domain, you need to set the Path to be the entire site, probably like this:
userSelectedTheme.Path = "/";
More info:
http://msdn.microsoft.com/en-us/library/system.web.httpcookie.path(v=vs.110).aspx
All I had to do was put the preinit code in the code files of the other pages.

Asp.net listview does not display data correctly

My problem is that when i display data in listview for first time then it show correctly but when i display data second time then listview does not update the data correctly. I have made a function for databinding with listview which i have called in pageLoad and some other method.
Can anyone please give me a solution about this ?
I have also uploaded my source code for more detail.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListView();
}
}
protected void LoadDataIntoListView()
{
Users objQuery = new Users();
string adminID = "Here is my query to get the data from MS-SQL";
objQuery.ExecuteSql(str);
if (objQuery.RowCount > 0)
{
Title = "Row affected";
lstAppointments.Items.Clear();
lstAppointments.DataSource = objQuery.DefaultView;
lstAppointments.DataBind();
}
else
{
Title = "None Row affected";
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
string caseID = (string)Session["caseID"];
//string updateQuery = "update Cases set sCaseStatus='cancel' where iCaseID= '" + caseID + "'";
Cases objCases = new Cases();
objCases.LoadByPrimaryKey(Convert.ToInt32(caseID));
if (String.Equals(objCases.SCaseStatus, "cancel"))
{
Page.Title = "No Update";
ModalPopupExtender1.Hide();
}
else
{
objCases.SCaseStatus = "cancel";
objCases.Save();
Page.Title = "No Update";
ModalPopupExtender1.Hide();
lstAppointments.Items.Clear();
LoadDataIntoListView();
}
}
Thanks in advance.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadDataIntoListView();
}
}
You are binding data in not Postback. That means it does not binds data when you postback to same page. If you want to bind that on every page load, call the function LoadDataIntoListView() in Page_Load

Two dropdown in a page ( conflict )

Two dropdownlists drop1, drop2 have separate selected index changed. Any dropdown, on selectedindexchanged, goes to another page. If we use back button in browser it goes back to our home page and one of dropdown will be selected position. If we change the other dropdown, it works only the first selected index changed in the coding section
How can we solve this problem?
code
protected void Page_Load(System.Object sender, System.EventArgs e)
{
try
{
if (!Page.IsPostBack)
{
string zCenterId="0";
if(Request.QueryString["LCID"]!=null)
{
zCenterId = Request.QueryString["LCID"].ToString();
}
ManageActivityAdminUIController ObjCtrl = new ManageActivityAdminUIController();
List<ManageActivityAdminUIInfo> ObjInfo = ObjCtrl.GetActivityList(zCenterId );
drplistactivity.DataSource = ObjInfo;
drplistactivity.DataBind();
drplistactivity.DataSource = ObjInfo;
drplistactivity.DataTextField = "ActivityName";
drplistactivity.DataValueField = "ID";
drplistactivity.DataBind();
drplistactivity.Items.Insert(0, new ListItem("<--Select Activity-->", "0"));
ManageCoursesController ObjCtrl = new ManageCoursesController();
List<ManageCoursesInfo> ObjInfo = ObjCtrl.GetCourses(zCenterId );
drplistcourse.DataSource = ObjInfo;
drplistcourse.DataTextField = "CourseName";
drplistcourse.DataValueField = "ID";
drplistcourse.DataBind();
drplistcourse.Items.Insert(0, new ListItem("<--Select Course-->", "0"));
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
protected void drplistactivity_SelectedIndexChanged(object sender, EventArgs e)
{
string url = ResolveClientUrl("~/Activity.aspx?ActivityId="+drplistactivity.SelectedItem.Value);
Response.Redirect(url);
}
protected void drplistcourse_SelectedIndexChanged(object sender, EventArgs e)
{
string url = ResolveClientUrl("~/Course.aspx?CourseId=" + drplistcourse.SelectedItem.Value);
Response.Redirect(url);
}
If ViewState is off (on the dropdown or any of its parents - all the way up to the page) then the event won't fire. (It should post back though...)
The problem seems to be caused by the caching of your page.
I'd say that your two events are triggered, but you can not see it because of redirect
You may disable caching of your form :
HttpContext.Current.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
HttpContext.Current.Response.Cache.SetValidUntilExpires(false);
HttpContext.Current.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
HttpContext.Current.Response.Cache.SetNoStore();
Response.Expires = -1;
or you may test the eventtarget inside your eventhandlers
protected void drplistcourse_SelectedIndexChanged(object sender, EventArgs e)
{
if(drplistcourse.UniqueID!=Request.Form["__EVENTTARGET"])
return;
string url = ResolveClientUrl("~/Course.aspx?CourseId=" + drplistcourse.SelectedItem.Value);
Response.Redirect(url);
}

How can I redirect based on a selection of a DropDownList

I have a TextBox1 and a Search button in my application with this following code:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("~\\searchpage.aspx?PatientNRIC=" + TextBox1.Text);
}
Which means, if the user type ONLY IC NO:S1234567D, then when click it will show the patient detailview.
So I now I'm doing almost the same thing but now I have a TextBox2 and a DropDownList1. Inside DropDownList1, I have "Name", "IC No", "Test_Date".
So for an example, I type "S1234567D" in the textbox1, and I choose "IC No" in DropDownList1 it should redirect me to a page of the S1234567D's patient detailview.
How could I do my code? Thanks!
Something like the following might work for you:
protected void Button1_Click(object sender, EventArgs e)
{
if(dropdownlist1.SelectedValue == "IC No")
{
// assuming this is the redirect to your patients details view
// but you MUST use only forward slashes to make it work (!)
Response.Redirect("~/searchpage.aspx?PatientNRIC=" + TextBox1.Text);
}
}
name.Text = ddl1.DataTextField;
ICNo.Text = ddl1.DataValueField;
textBox1.Text = name.text+ICno.Text;
protected void Button1_Click(object sender, EventArgs e)
{
if(textbox1 != null)
{
Response.Redirect("~/searchpage.aspx?PatientNRIC=" + TextBox1.Text);
}
}
}

Categories

Resources