How can I prevent the LinqDataSource Where clause from resetting on postback? - asp.net

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

Related

Why is my UserControl's ViewState partially saved?

I have a user control that makes substantial use of this.ViewState["Key"] = SomeValue. Most of it is loaded from my Page_Init():
protected void Page_Init(object sender, EventArgs e)
{
if(!IsPostBack)
{
ViewState["Blahblah"] = LoadSomeValue();
}
}
The rest are set at various points.
But for some reason it's unavailable on subsequent postbacks. I overrode SaveViewState() to check, and only like three of them are saved!
protected override object SaveViewState()
{
List<object> viewStateObjectsBefore = ViewState.OfType<object>().ToList();
object ret = base.SaveViewState();
List<object> viewStateObjectsAfter = ViewState.OfType<object>().ToList();
GC.KeepAlive(viewStateObjectsBefore);
GC.KeepAlive(viewStateObjectsAfter);
GC.KeepAlive(ret);
return ret;
}
Both viewStateObjectsBefore and viewStateObjectsAfter contain 10 key/value pairs, but ret only contains three!
Added: Moving the initializations to Page_Load() is not an easily available option, because the initializations must be done before the parent's Page_Load() executes.
Adding a call to SetDirty() at the end of my Page_Init() solved the problem:
protected void Page_Init(object sender, EventArgs e)
{
if(!IsPostBack)
{
ViewState["Blahblah"] = LoadSomeValue();
//Looks like the ViewState is not yet "tracking" changes before Page_Load.
//The items have to be marked as "dirty" manually so they'll be included by SaveViewState().
ViewState.SetDirty(true);
}
}

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")
{
...
}
...
}

Select all items in listbox when updated via UpdatePanel

protected void Page_Load(object sender, EventArgs e)
{
if (ScriptManager.GetCurrent(this).IsInAsyncPostBack)
{
string id = ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID;
if (id == cboGroup.UniqueID)
{
foreach (ListItem i in lstTest.Items)
i.Selected = true;
}
}
}
This code runs when my cboGroup causes my UpdatePanel to refresh which has the lstTest in it and the data inside of it gets updated, but it does NOT select them all. How can I make it so when my UpdatePanel is finished refreshing all elements of the list box that it refreshed get selected?
[edit] I'm noticing now that at this point what's in the listbox is the previous values and not the new values I would need. So this seems to be before the listbox is filled with data (which is via a SqlDataSource) so it's probably overwriting this.
I was able to put my selection code in the list box's DataBound() event.
protected void lstTest_DataBound(object sender, EventArgs e)
{
SelectAllTest();
}

How can this codebehind be written better?

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.

Read data from SqlDataSource or GridView

I have SqlDataSource and GridView on web form. GridView.DataSourceID = mySqlDataSource.
When I call myGridView.DataBind(), all data successfully bind on the page.
How is it possible to read already got data from mySqlDataSource or myGridView objects as DataTable or DataView? Thanks
The data in the gridview can read by using FindControl property of Gridview control. For example, for reading values set in the Checkbox column in the grid.
for (i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox chk = (CheckBox)GridView1.Rows[i].FindControl("checkbox1");
//here code for using value captured in chk
}
Provided your data set isn't gigantic, you could store it in the Session, bind your GridView to the Session data, and then re-use the Session data in your other web objects.
Your code would then look something like this (you'll have to forgive any minor inaccuracies -- I'm away from my development box at the moment):
protected override OnInit(object sender, EventArgs e)
{
base.OnInit();
if (Page.IsPostback == false)
{
SetSessionData();
}
//
// Set your GridView, DataTable, DataView, etc. events here.
//
}
void SetSessionData();
{
List<YourDataBoundObject> myDataBoundObject = GetYourDataBoundObject(); // Or Collection<T>, IEnumerable<T>, etc.
Session["data"] = myDataBoundObject;
}
void YourGridView_Load(object sender, EventArgs e)
{
BindYourGridView();
}
void BindYourGridView()
{
YourGridView.DataSource = GetSessionData();
YourGridView.DataBind();
}
List<YourDataBoundObject> GetSessionData()
{
return (List<YourDataBoundObject>) Session["data"];
}
void YourDataTable_Load(object sender, EventArgs e)
{
BindYourDataTable();
}
void BindYourDataTable()
{
YourDataTable.DataSource = GetSessionData();
YourDataTable.DataBind();
}

Resources