Save data for UserControl to ViewState - c#

At my user-control I populate listbox with collection and want save data in viewstate\controlstate for further autopostback using.
protected void btFind_Click(object sender, EventArgs e)
{
var accounts = new AccountWrapper[2];
accounts[0] = new AccountWrapper { Id = 1, Name = "1" };
accounts[1] = new AccountWrapper { Id = 2, Name = "2" };
lbUsers.DataSource = accounts;
lbUsers.DataBind();
ViewState["data"] = accounts;
}
ListBox is populated at button click. When I save accounts to ViewState listBox is empty, when not it displays collection good. What's reasonn of this behaviour?

After your button is being clicked, PostBack occurs and ListBox loses it's state.
void lbUsers_DataBinding(object sender, EventArgs e)
{
if (this.IsPostBack &&)
{
AccountWrapper[] accounts = this.ViewState["data"] as AccountWrapper[];
if (accounts!= null)
{
lbUsers.DataSource = accounts;
lbUsers.DataBind();
}
}
}
(don't forget to subscribe to DataBinding event of your ListBox in markup)
Also I recommend you to encapsulate your access to ViewState:
private AccountWrapper[] Accounts
{
get { return this.ViewState["data"] as AccountWrapper[]; }
set { this.ViewState["data"] = value;
}

Related

DataGridView not loading data programmatically

I am working on a Windows application where I get an input from a TextBox and add it to the DataGridView when user clicks on a Button (Add).
My problem is that when I add the text for the first time, it works fine and its added to the grid.
When I add new text, it's not added to the DataGridView. Once the Form is closed and reopened with the same object then I am able to see it.
Code:
private void btnAddInput_Click(object sender, EventArgs e)
{
if (Data == null)
Data = new List<Inputs>();
if (!string.IsNullOrWhiteSpace(txtInput.Text))
{
Data.Insert(Data.Count, new Inputs()
{
Name = txtInput.Text,
Value = string.Empty
});
}
else
{
MessageBox.Show("Please enter parameter value", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
txtInput.Text = "";
gridViewInputs.DataSource = Data;
}
I am not sure what is causing the record not to be added to grid on second add button click.
You could set the DataGridView.DataSource to null before setting a new one.
This would cause the DataGridView to refresh its content with the new data in the source List<Inputs>:
the underlying DataGridViewDataConnection is reset only when the DataSource reference is different from the current or is set to null.
Note that when you reset the DataSource, the RowsRemoved event is raised multiple times (once for each row removed).
I suggest to change the List to a BindingList, because any change to the List will be reflected automatically and because it will allow to remove rows from the DataGridView if/when required: using a List<T> as DataSource will not allow to remove a row.
BindingList<Inputs> InputData = new BindingList<Inputs>();
You can always set the AllowUserToDeleteRows and AllowUserToAddRows properties to false if you don't want your Users to tamper with the grid content.
For example:
public class Inputs
{
public string Name { get; set; }
public string Value { get; set; }
}
internal BindingList<Inputs> InputData = new BindingList<Inputs>();
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = InputData;
}
private void btnAddInput_Click(object sender, EventArgs e)
{
string textValue = txtInput.Text.Trim();
if (!string.IsNullOrEmpty(textValue))
{
InputData.Add(new Inputs() {
Name = textValue,
Value = "[Whatever this is]"
});
txtInput.Text = "";
}
else
{
MessageBox.Show("Not a valid value");
}
}
If you want to keep using a List<T>, add the code required to reset the DataGridView.DataSource:
private void btnAddInput_Click(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textValue))
{
//(...)
dataGridView1.DataSource = null;
dataGridView1.DataSource = InputData;
txtInput.Text = "";
}
//(...)

Retrieving value from combo box selected item

I am using Windows Application.I Put some data as direct values in combo box.I defined var type to combo box.I put these combo box on form load.Now I want to retrieve the value of selected item on my button2_click event and I tried below code to retrieve it,but it giving me error of The name comboBox does not exist in current context.Can any one suggest me how to fix it.
namespace WinDataStore
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
var daysOfWeek =
new[] { "RED", "GREEN", "BLUE"
};
// Initialize combo box
var comboBox = new ComboBox
{
DataSource = daysOfWeek,
Location = new System.Drawing.Point(180, 140),
Name = "comboBox",
Size = new System.Drawing.Size(166, 21),
DropDownStyle = ComboBoxStyle.DropDownList
};
// Add the combo box to the form.
this.Controls.Add(comboBox);
}
private void button1_Click(object sender, EventArgs e)
{
// Create a new instance of FolderBrowserDialog.
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
// A new folder button will display in FolderBrowserDialog.
folderBrowserDlg.ShowNewFolderButton = true;
//Show FolderBrowserDialog
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
//Show selected folder path in textbox1.
textBox1.Text = folderBrowserDlg.SelectedPath;
//Browsing start from root folder.
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
if (!textBox1.Text.Equals(String.Empty))
{
if (System.IO.Directory.GetFiles(textBox1.Text).Length > 0)
{
foreach (string file in System.IO.Directory.GetFiles(textBox1.Text))
{
//Add file in ListBox.
listBox1.Items.Add(file);
}
}
else
{
// listBox1.Items.Add(String.Format(“No files Found at location:{0}”, textBox1.Text));
}
}
string s = (string)comboBox.SelectedItem;
listBox1.Items.Add(s);
}
}
}
comboBox was local variable in Form1 .ctor. You can't access it from another method
options:
1) access to the control by name
private void button2_Click(object sender, EventArgs e)
{
var comboBox = this.Controls["comboBox"] as ComboBox;
...
}
2) make it a private member of the form as controls normally are, if they are created in designer
ComboBox comboBox;
public Form1()
{
InitializeComponent();
// Initialize combo box
comboBox = new ComboBox() {...};
...
}
Currently the Combobox appears to be a local variable. Try to make it a global field variable and you should be able to access it.

How to save a page state?

In a Windows Runtime app, I load data like this:
private async void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
var userId = e.NavigationParameter as string;
List<User> followers = GetFollowers(userId);
this.DefaultViewModel["Followers"] = followers;
}
then user can select an item from ListView:
private void ContentListView_ItemClick(object sender, ItemClickEventArgs e)
{
var selectedItem = e.ClickedItem as User;
if (!Frame.Navigate(typeof(FollowersPage), selectedItem.UserId))
{
throw new Exception(this.resourceLoader.GetString("NavigationFailedExceptionMessage"));
}
}
So it navigates forward to the same page, but shows new followers.
The problem is that when it navigates back, it loads data again and shows from the beginning of the list rather than showing the last item selected.
So how to save a List of data in NavigationHelper_SaveState and how to load it again in NavigationHelper_LoadState with last position in the list? thanks.
Here's a basic semi-tested example you can start from. You'll need to modify it to fit your exact circumstances. Some of it is adapted from here.
void NavigationHelper_SaveState(object sender, SaveStateEventArgs e)
{
var isp = (ItemsStackPanel)listview.ItemsPanelRoot;
int firstVisibleItem = isp.FirstVisibleIndex;
e.PageState["FirstVisibleItemIndex"] = firstVisibleItem;
// This must be serializable according to the SuspensionManager
e.PageState["Followers"] = this.DefaultViewModel["Followers"];
}
void NavigationHelper_LoadState(object sender, LoadStateEventArgs e)
{
// Do we have saved state to restore?
if (e.PageState != null)
{
// Restore list view items
this.DefaultViewModel["Followers"] = (WhateverType)e.PageState["Followers"];
// Restore scroll offset
var index = (int)e.PageState["FirstVisibleItemIndex"];
var container = listview.ContainerFromIndex(index);
listview.ScrollIntoView(container);
}
else
{
// Load data for the first time
var userId = e.NavigationParameter as string;
List<User> followers = GetFollowers(userId);
this.DefaultViewModel["Followers"] = followers;
}
}

How to pass data between forms?

I am developing a desktop application in which I want to get information from user. If user selects particular radio button then I am opening a new form in popup in which I have placed checked list box. After selecting values from check box I want to access selected value in the previous form. Below are images that can clear idea.
When user click on radio button in "Enable conent type" (as highlighted in the screen) a new form in popup is open to select values from checked list box. After selecting desired value , press "Select" button from Select Content Type form.
Now the form will be hidden but I want to get the selected values in the form "Create Lists".
My code for Radio Button event is:
private void rdbEnableCtypeYes_CheckedChanged(object sender, EventArgs e)
{
if (rdbEnableCtypeYes.Checked)
{
lblSelectContentType.Visible = true;
frmSelectContentType selectContentType = new frmSelectContentType();
selectContentType.rootWebUrl = rootWebUrl;
selectContentType.MdiParent = this.MdiParent;
selectContentType.StartPosition = FormStartPosition.CenterScreen;
selectContentType.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
selectContentType.Show();
}
else
{
lblSelectContentType.Visible = false;
cmbContentType.Visible = false;
}
}
My code for form of Select content type is:
public string rootWebUrl = string.Empty;
XDocument contentTypeFile = XDocument.Load(FilePaths.ContentTypesFilePath);
private void frmSelectContentType_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(rootWebUrl))
{
if (contentTypeFile != null)
{
XElement xSiteCollection = contentTypeFile.Descendants(XmlElements.SiteCollection).Where(x => x.Attribute(XmlAttributes.Url).Value.Equals(rootWebUrl)).FirstOrDefault();
if (xSiteCollection != null)
{
IEnumerable<XElement> xContentTypes = xSiteCollection.Descendants(XmlElements.ContentType);
if (xContentTypes.OfType<XElement>().Count() > 0)
{
foreach (XElement xContentType in xContentTypes)
{
ComboboxItem item = new ComboboxItem();
item.Text = xContentType.Attribute(XmlAttributes.Name).Value;
item.Value = xContentType.Attribute(XmlAttributes.Id).Value;
lstContenType.Items.Add(item);
}
}
}
}
}
}
What should I do?
Try This.
Select Content Type Form
private List<string> _selectedItems = new List<String>();
public List<string> SelectedItem
{
get {return _selectedItems;}
}
private void btnSelect_Click(object sender, EventArgs e)
{
for(int i=0; i<lst.Items.Count;i++)
{
if (lstContenType.GetItemCheckState(i) == CheckState.Checked)
_selectedItems.Add(lst.Items[i].ToString());
}
this.Close();
}
Create List Form
private void rdoEnableCntType_Checked(object sender, EventArgs e)
{
if (rdoEnableCntType.Checked = true)
{
FrmConentType frm = new FrmConentType();
frm.ShowDialog();
List<string> list = frm.SelectedItems;
//Place your code to use selected items
}
}
You can pass data in the Constructor of FormB. For example:
//Default Constructor
public FormB()
{
InitializeComponent();
}
// Overloaded Constructor
public FormB(string parameter1, string parameter2, string parameter3)
{
InitializeComponent();
}
For example:
public FormB(bool RbuttonChecked)
{
InitializeComponent();
if(RbuttonChecked)
{
//Code
}
}
Invoke FormB from FormA like:
FormB obj=new FormB(Rbtn.checked); //Invoking the overloaded constructor
obj.Show();
You can defined a list in the main form to store items user selected in "Select Content Type" windows. When user have finished the window "Select Content Type", you add selected items to the variable.
In Form "Create List" class:
public List<ContentType> selectedContentTypes = new List<ContentType>();
When user press "Select" button in form "Select Content Type", add items to the variable:
// For each selected items in the listbxo {
frmCreateList.selectedContentTypes.Items.Add(itemId);
// }
If you can post your source code, it would be easier to help.

Maintaning my choices on GridView Checkbox

I have this Module in my project in which I have 2 gridviews. One is for the Main MenuModule and the other one is for it's subMenu. I created a List so that when a row on my Main Menu Module has been checked and it has a corresponding submenu, it will show on the SubMenu Gridview.
Now, I can see my SubMenuGridview when I get back to that page (I used session), but I noticed that the checkbox I ticked were all gone.
My problem was on how can my page remember the checkboxes I checked, both from my Main Menu Module gridview and from my Submenu gridview.
protected void cbxSelect_CheckedChanged(object sender, EventArgs e)
{
SubMenuGrid.DataSource = null;
SubMenuGrid.DataBind();
Business.SubMenuModules sub = new Business.SubMenuModules();
List<oSubList> oList = new List<oSubList>();
int counter = 0;
foreach (GridViewRow nRow in gvModuleList.Rows)
{
Int32 intModID = Convert.ToInt32(nRow.Cells[0].Text);
CheckBox chkBx = (CheckBox)nRow.FindControl("cbxSelect");
if (chkBx.Checked == true)
{
counter = counter + 1;
var oModList = sub.GetAllMenuPerModuleID(intModID);
if (oModList.Count > 0)
{
foreach (var rec in oModList)
{
oSubList olist = new oSubList
{
ID = rec.ID,
ModuleID = rec.ModuleID,
Submenu = rec.Submenu,
Description = rec.Description
};
oList.Add(olist);
}
Session["list"]=oList;
SubMenuGrid.DataSource = oList;
SubMenuGrid.DataBind();
}
}
}
}
This can be done using:
ViewState
SessionPageStatePersister
Custom Session based solution
For view state-see the below posted link in comments..
Custom Session based solution
We are going to use the pre render method.
This method is being invoked after the page has been initialized but before it saved its ViewState and rendered.
Are are going to load the Request.Form into a session variable and load it back with each call to the page that is not a postback.
protected void Page_PreRender(object sender, EventArgs e)
{
if (!Page.IsPostBack && Session["PageState"] != null)
{
NameValueCollection formValues = (NameValueCollection)Session["PageState"];
String[] keysArray = formValues.AllKeys;
for (int i = 0; i < keysArray.Length; i++)
{
Control currentControl = Page.FindControl(keysArray[i]);
if (currentControl != null)
{
if (currentControl.GetType() == typeof(System.Web.UI.WebControls.TextBox)) ((TextBox)currentControl).Text = formValues[keysArray[i]];
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.CheckBox))
{
if (formValues[keysArray[i]].Equals("on")) ((CheckBox)currentControl).Checked = true;
}
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
((DropDownList)currentControl).SelectedValue = formValues[keysArray[i]].Trim();
}
}
}
if(Page.IsPostBack) Session["PageState"] = Request.Form;
}
SessionPageStatePersister
The abstract PageStatePersister class represents the base class that encapsulates the Page State storage and processing.
Storage can be done with the default HiddenFieldPageStatePersister class or with SessionPageStatePersister.
When SessionPageStatePersister is used, the .NET Server manages the _VIEWSTATE in a session object instead of a hidden field on your form.
Changing the state storage looks like this:
protected override PageStatePersister PageStatePersister
{
get
{
return new SessionPageStatePersister(this);
}
}

Categories