How can this codebehind be written better? - asp.net

I have a form which has a single textbox that sends some data to the database upon hitting enter. Data is displayed below the textbox in a repeater control. Input data is displayed on the form immediately by binding the data to the repeater in the TextChanged event of that textbox.
In the CodeBehind, I am calling BindRepeater method twice, once on every new page load and once on the TextChanged event of the textbox.
How can this be rewritten to call the BindRepeater only once and still achieve the same effect?
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
BindRepeater();
}
}
protected void BindRepeater()
{
// data retrieval
// repeater binding
}
protected void CreateData(string newdata)
{
// data insert
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
if (TextBox1.Text != string.Empty)
{
string _newData = TextBox1.Text.Trim();
CreateData(_newData);
BindRepeater();
}
}

Use an event that would be fired after the text changed event to do the binding in. you can now remove it from the page load event.

Related

Losing data after postback in ASP.net C#

i'm binding datalist control from database in !page.ispostback page event, when i hit any button the page postback and i lose datalist data source,so what i shall do to prevent losing data? deplucate the code in postback event or what?
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
try
{
Session["ClinicID"] = "1";
c.FillDataList(DataList1, "SP_GET_PATIENTS_LIST", "#CLINICID", int.Parse(Session["ClinicID"].ToString()), lblmsg);
updPatientsList.Update();
}
catch (Exception)
{
}
}
}

How to update CheckBoxes on the client side after making changes on the server side?

I have a DropDownList and a CheckBox on my web form. After the DropDownList is clicked and this event is posted back to the server. DropDownList_SelectedIndexChanged event is called on the server side. Inside that event handler, I have CheckBox.Checked = true, But I couldn't make the page on the client side to reflect this change (CheckBox.Checked = true). How do I achieve this? Or am I in the wrong direction to use the DropDownList's event handler to update the CheckBox because the page firstly reloads and then DropDownList_SelectedIndexChanged is called?
Page load method:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.DropDownList1.Items.Clear();
AddItemsToDropDownList();
}
}
DropDownList selected index changed event handler:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var selected = this.DropDownList1.SelectedItem.Text;
CheckBox checkBox = GetCheckBoxToBeSetByText(selected);
checkBox.Checked = true;
}
OK. Found the issue. Actually there is nothing wrong with the code in my original post. But to make a smallest sample when I posted, I removed some "extra" code. The below is the "complete" code (OK, fine, I still removed some code). As you can see, I put the CheckBox into a static Dictionary. Each time the SelectedIndexChanged event handler is called, it's modifying the CheckBox in that static Dictionary, which means it's modifying the CheckBox object created from the last session? (still not clear here) Looks like each time when a postback message is received, a new set of CheckBox objects are created. Bear with me if this is known to everybody here already because I only have two days of experience on this web development thing up to today.
private static Dictionary<Environment, CheckBox> EnvironmentsCheckBoxes;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
EnvironmentsCheckBoxes = new Dictionary<Environment,CheckBox>();
EnvironmentsCheckBoxes.Add(Environment.Dev1, this.Dev1_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.Dev2, this.Dev2_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.QA, this.QA_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.QA2, this.QA2_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.Demo, this.Demo_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.Prod, this.Prod_CheckBox);
EnvironmentsCheckBoxes.Add(Environment.UAT, this.UAT_CheckBox);
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var selected = this.DropDownList1.SelectedItem.Text;
if (selected == "Dev1")
{
EnvironmentsCheckBoxes[Environment.Dev1].Checked = true;
}
else if (selected == "Dev2")
{
...
}
...
}

How to know the previous event handled in asp.net

on page load i have shown data from database onto a gridview(with edit and delete option). I also have a search button on the page. when i click on search the searched data should be visible in the gridview, which is working fine. But when i click on delete link after search it does not take the searched row. The page postsback after clicking on delete. I need to check the event performed prior to event performed on gridview. How to do that?? I hope that the issue is clear.. Any help is appreciated. Thanks.
Page_Load occurs before RowCommand, are you only binding grid if(!IsPostBack) ?
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
BindGrid();
}
}
protected void SearchButton_Click(object sender, EventArgs e)
{
BindGrid(searchText.Text);
}
protected void GridView_RowCommand(object sender, GridViewRowEventArgs e)
{
switch(e.CommandName)
{
case "Delete":
DeleteRow(e.Row.CommandArgument);
break;
}
}
private void BindGrid()
{
//GridView binding business logic.
}
private void BindGrid(String searchTerm)
{
//GridView binding logic with searchTerm.
}
private void DeleteRow(String commandArg)
{
//Convert command arg to ID or whatever and delete data.
}

When events fire, page starts from defaults

I've a Calendar on my webpage, and during the page_load event I'm setting the webpage to take today's date and load the data for today's date in the Gridview. Paging is allowed in the Gridview.
I also have a Calendar_Selectiondate event and when someone clicks on a date in the calendar, it will show data for that date. The date value is showed in a session variable. In this scenario when I click on the paging hyperlink 2, it will take me to the current day's second page instead of the selected day's second page. I know this is because it's going through the Page_Load event whenever I click on that hyperlink 2 and the date is getting set to Today's date instead of the selected date.
public partial class UKMail_UKMail7Day : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Calendar.SelectedDate = DateTime.Today;
Session["MailDate"] = Calendar.SelectedDate;
UKMail7DayGridView.DataSourceID = "UKMail7DaySelected";
UKMail7DayGridView.DataBind();
//UKMail7DayGridView.DataSourceID = "UKMail7DayAllData";
//UKMail7DayGridView.DataBind();
}
protected void Calendar_SelectionChanged(object sender, EventArgs e)
{
Session["MailDate"] = Calendar.SelectedDate;
UKMail7DayGridView.DataSourceID = "UKMail7DaySelected";
UKMail7DayGridView.DataBind();
}
}
The events in your Page_Load execute no matter what triggers the postback. If you have code that should ONLY happen the FIRST time a page is loaded, put it within an if(!Page.IsPostback) block.
void Page_Load(object sender, EventArgs e)
{
// code that will execute on every postback, button click, etc.
if(!Page.IsPostback)
{
//code that will only execute the first time the page is loaded.
}
}
Strongly recommended reading: (Every ASP.NET developer should know this.) http://msdn.microsoft.com/en-us/library/ms178472.aspx
Edit using your updated code:
public partial class UKMail_UKMail7Day : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostback)
{
Calendar.SelectedDate = DateTime.Today;
Session["MailDate"] = Calendar.SelectedDate;
UKMail7DayGridView.DataSourceID = "UKMail7DaySelected";
UKMail7DayGridView.DataBind();
//UKMail7DayGridView.DataSourceID = "UKMail7DayAllData";
//UKMail7DayGridView.DataBind();
}
}
protected void Calendar_SelectionChanged(object sender, EventArgs e)
{
Session["MailDate"] = Calendar.SelectedDate;
UKMail7DayGridView.DataSourceID = "UKMail7DaySelected";
UKMail7DayGridView.DataBind();
}
}
In the page load event, set this
if(Page.IsPostback)
return;
Do this before any of your other code so it wont be executed on postback. I hope I understood you correctly.

How can I prevent the LinqDataSource Where clause from resetting on postback?

I'm trying to set the where clause on a LinqDataSource object bound to a GridView programmatically on a button click, but when the GridView rebinds data (for instance, when the user sorts) the Where clause resets back to the empty string. Is there a way to prevent this, or is there a better way to filter my results?
Perhaps you just add a ViewState property into your page/user control and then retrieve it on all post back?
public string MyLinqSourceWhere
{
get { return (string)this.ViewState["MyLinqSourceWhere"]; }
set { this.ViewState["MyLinqSourceWhere"] = value; }
}
public void Page_Load(object sender, EventArgs e)
{
this.myLinqSource.Where = this.MyLinqSourceWhere;
}
public void Button1_Click(object sender, EventArgs e)
{
this.MyLinqSourceWhere = " .... ";
this.myLinqSource.Where = this.MyLinqSourceWhere;
}
If that doesn't work, then perhaps bind on the LinqDataSource.Selecting event the fetch property from the viewstate to your where clause?? It all depends

Resources