Accessing dynamically generated dropdownlist in Gridview_RowUpdating event - c#

I am using Gridview with AutoGenerateColumns="True", so gridview columns are generated dynamically. Now in case of edit, I am adding dropdownlist dynamically for one of the field in the gridview. Please see following code:
protected void grdViewConfig_RowEditing(object sender, GridViewEditEventArgs e)
{
grdViewConfig.EditIndex = e.NewEditIndex;
BindGridView();
clientBAL = new TMIWsBALClient();
var lstAppIds = clientBAL.GetDistinctApplicationIds();
GridViewRow grdRow = grdViewConfig.Rows[e.NewEditIndex];
for (int i = 0; i < grdRow.Cells.Count; i++)
{
if (grdRow.Cells[i].GetType().Equals(typeof(DataControlFieldCell)))
{
DataControlFieldCell dcField = (DataControlFieldCell )grdRow.Cells[i];
if (dcField.ContainingField.HeaderText.ToLower().Equals("applicationid"))
{
DropDownList drpDwnAppIds = new DropDownList();
drpDwnAppIds.ID = "drpDwnAppIds";
drpDwnAppIds.DataSource = lstAppIds;
drpDwnAppIds.DataBind();
var tb = dcField.GetAllControlsOfType<TextBox>(); ;// grdRow.Cells[i].GetAllControlsOfType<TextBox>();
TextBox firstTb = (TextBox)tb.First();
foreach (ListItem lstItem in drpDwnAppIds.Items)
{
if (firstTb.Text.Equals(lstItem.Text, StringComparison.CurrentCultureIgnoreCase))
{
lstItem.Selected = true;
}
}
dcField.Controls.Remove(firstTb);
dcField.Controls.Add(drpDwnAppIds);
}
}
}
}
Now in Gridview_RowUpdating event, I am trying to fetch the dropdownlist in similar way, but I am unable to get it. GetAllControlsOfType() is an extension method, which will return all the child controls under selected parent. In this case, parent is gridview cell and child control is dropdownlist. But it is returning null.
protected void grdViewConfig_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
strTableName = txtTable.Text.Trim();
string strAppId;
GridViewRow grdRow = grdViewConfig.Rows[grdViewConfig.EditIndex];
for (int i = 0; i < grdRow.Cells.Count; i++)
{
if (grdRow.Cells[i].GetType().Equals(typeof(DataControlFieldCell)))
{
DataControlFieldCell dcField = (DataControlFieldCell)grdRow.Cells[i];
if (dcField.ContainingField.HeaderText.ToLower().Equals("applicationid"))
{
var drpDwn = dcField.GetAllControlsOfType<DropDownList>();
DropDownList drpDwnAppIds = (DropDownList)drpDwn.First();
strAppId = drpDwnAppIds.SelectedValue;
}
}
}
}
What am I missing? Please help. Also let me know if more information is needed.
Thank you in advance.

Dynamically generated controls need to be recreated on every postback. In your case the DropDownList controls you created no longer exist when you hit the grdViewConfig_RowUpdating handler.
Generally in this sort of case you would set AutoGenerateColumns to false and manually define your columns which would allow you to define a TemplateField which contains an ItemTemplate for read only mode and an EditItemTemplate for edit mode which could then contain your DropDownList.

Related

Change visible state of DataGridView only given its name

I have a form application where multiple DataGridView objects are to be displayed (but not at once). They should be created on top of each other and it should then be possible to toggle the displayed DataGridView using a ComboBox.
I have a function which should create new DataGridView every time its called and then adds the name to the ComboBox:
private void readCSV(string DBname)
{
DataGridView tagDBname = new DataGridView();
tagDBname.Location = new System.Drawing.Point(24, 260);
tagDBname.Name = DBname;
tagDBname.Size = new System.Drawing.Size(551, 217);
tagDBname.TabIndex = 6;
tagDBname.Columns.Add("Column1", "Col1");
tagDBname.Columns.Add("Column2", "Col2");
tagDBname.Visible = false;
comboBoxTag.Items.Add(DBname);
}
Then I would like to change the visibility state of a DataGridView given the selected name from the ComboBox. This should be done in the function called when the index changes:
private void comboBoxTag_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the name of the DataGridView which should be visible:
string selectedTagDB = comboBoxTagDatabases.SelectedItem.ToString();
DataGridView tagDatabase = ? // Here the DataGridView should be selected given the name "selectedTagDB"
tagDatabase.Visible = true;
}
In the above, I do not know how to assign the DataGridView only given its name. Any help would be appreciated - even if it means that the selected approach is inappropriate of what I am trying to achieve. If the question is answered elsewhere, feel free to guide me in the right direction :)
I would store the gridviews in a dictionary by using the DB name as key;
private readonly Dictionary<string, DataGridView> _tagDBs =
new Dictionary<string, DataGridView>();
private void readCSV(string DBname)
{
DataGridView tagDBname = new DataGridView();
// Add the gridview to the dictionary.
_tagDBs.Add(DBname, tagDBname);
tagDBname.Name = DBname;
tagDBname.Location = new System.Drawing.Point(24, 260);
tagDBname.Size = new System.Drawing.Size(551, 217);
tagDBname.TabIndex = 6;
tagDBname.Columns.Add("Column1", "Col1");
tagDBname.Columns.Add("Column2", "Col2");
tagDBname.Visible = false;
this.Controls.Add(tagDBname); // Add the gridview to the form ot to a control.
comboBoxTag.Items.Add(DBname);
}
private void comboBoxTag_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the name of the DataGridView which should be visible:
string selectedTagDB = comboBoxTagDatabases.SelectedItem.ToString();
foreach (DataGridView dgv in _tagDBs.Values) {
dgv.Visible = dgv.Name == selectedTagDB; // Hide all gridviews except the selected one.
}
}
If you need to do something with the selected gridview, you can get it with:
if (_tagDBs.TryGetValue(selectedTagDB, out DataGridView tagDatabase)) {
// do something with tagDatabase.
}
Note: you must add the gridview to the form or to a container control on the form. E.g.
this.Controls.Add(tagDBname);
You can loop through all DataGridViews of the form to display the expected one using its name, while hidding the others ones.
This solution isn't pretty but works
private void ShowOneDataGridViewAndHideOthers(string name)
{
foreach (var DGV in this.Controls.OfType<DataGridView>())
{
DGV.Visible = DGV.Name == name;
}
}
And call it this way :
private void comboBoxTag_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the name of the DataGridView which should be visible:
string selectedTagDB = comboBoxTagDatabases.SelectedItem.ToString();
ShowOneDataGridViewAndHideOthers(selectedTagDB);
}
The method can be made a bit more generic this way :
private void ShowOneControlAndHideOthers<T>(string name, Control controls) where T : Control
{
foreach (var control in controls.Controls.OfType<T>())
{
control.Visible = control.Name == name;
}
}
private void comboBoxTag_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the name of the DataGridView which should be visible:
string selectedTagDB = comboBoxTagDatabases.SelectedItem.ToString();
ShowOneControlAndHideOthers<DataGridView>(selectedTagDB, this);
}

Retrieve value from dynamic dropdownlist in placeholder C#

I have dynamic drop down lists that are created based on what's selected in the list box.. When clicking confirm this is when the drop down lists are created. Clicking save is where I attempt to retrieve the values. However I am unable to retrieve that values that are in the drop down lists.
Code:
protected void btnConfirm_Click(object sender, EventArgs e)
{
int ID = 0;
foreach (string value in values)
{
MyStaticValues.alEdit.Add(value);
CreateEditForm(value, ID);
ID += 1;
}
if (values.count != 0)
{
btnSave.Visible = true;
btnConfirm.Enabled = false;
}
}//End of btnConfirm_Click
protected void CreateEditForm(string Value, int ID)
{//Creates an edit form for the value inserted.
string name = value;
//This part adds a header
phEditInventory.Controls.Add(new LiteralControl("<h2>" + name + "</h2>"));
phEditInventory.Controls.Add(new LiteralControl("<div class=\"clearfix\"></div>"));
//Create a label
Label lblName = new Label();
lblName.Text = "Name";
lblName.ID = "lblName" + ID;
lblName.CssClass = "control-label";
//Create a Drop Down List
DropDownList ddlName = new DropDownList();
ddlName.ID = "ddlName" + ID;
ddlName.CssClass = "form-control";
//Set default N/A Values For Drop Down List
ddlName.Items.Add(new ListItem("N/A", Convert.ToString("0")));
//The Rest of the Values are populated with the database
//Adds the controls to the placeholder
phEditInventory.Controls.Add(lblName);
phEditInventory.Controls.Add(ddlName);
phEditInventory.Controls.Add(new LiteralControl("<div class=\"clearfix\"></div>"));
} //End of CreateEditForm
protected void btnSave_Click(object sender, EventArgs e)
{
string name = "";
try
{
for (int i = 0; i < MyStaticValues.alEdit.Count; i++)
{
string nameID = "ddlName" + i.ToString();
DropDownList ddlName = (DropDownList)phEditInventory.FindControl(nameID);
name = ddlName.SelectedValue.ToString();
}
}
catch (Exception ex)
{
}
phEditInventory.Visible = false;
btnSave.Visible = false;
MyStaticValues.alEdit.Clear();
}//End of btnSave_Click Function
Your problem is that the dynamically created dropdown lists are not maintained on postback. When you click the Save button, a postback occurs, and the page is re-rendered without the dynamically created dropdowns. This link may help.
Maintain the state of dynamically added user control on postback?

Checkbox Checked Event for multiple dynamic Checkboxes

I have an aspx page where I dynamically create checkboxes and add them to a panel from data in a SQL database. I need to have only one checkbox checked at a time. I have tried and googled just about everything but I cannot get the right answer. How would I go about getting that done.
My code for creating the checkboxes
public void CreateTimeSelection()
{
DataSet times = GetTimes();
int i = 0;
foreach (DataTable table in times.Tables)
{
foreach (DataRow row in table.Rows)
{
CheckBox chkTime = new CheckBox();
i += 1;
chkTime.ID = row["Time"].ToString();
chkTime.AutoPostBack = true;
chkTime.Text = row["Time"].ToString();
chkTime.CheckedChanged += new EventHandler(this.CheckChanged_click);
pnlTimeSlots.Controls.Add(chkTime);
pnlTimeSlots.Controls.Add(new LiteralControl("<br />"));
}
}
}
Code for Checkbox event handlers
protected void CheckChanged_click(object sender, EventArgs e)
{
CheckBox chkSelect = (CheckBox)sender;
if (chkSelect.Checked == true)
{
//set other checkboxes to false
}
}

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);
}
}

RowCommand not getting fired on Dynamically created GridView

I am creating a gridview dynamically with a ButtonField and several BoundFields. ButtonField button type is LinkButton. If i run it the buttonclick triggers a post back but rowCommand is not triggered. It is not triggered even if i use AutogenerateSelectButton. The event is dyanamically bound. Code As follows:
protected void B_Search_Click(object sender, EventArgs e) //Search buttonclick that creates and displays the gridview
{
gd = getGridView(); //defines the gridview with columns and buttonfield
gd.DataSource = executeAdvanceSearch(); //retrieves data from DB as Dataset
gd.DataBind();
gd.RowCommand += new GridViewCommandEventHandler(gdView_RowCommand); //Rowcommand event binding
PlaceHolder1.Controls.Add(gd);
}
protected void gdView_RowCommand(object sender, GridViewCommandEventArgs e) //not getting triggered on postback
{
int index = Convert.ToInt32(e.CommandArgument);
GridView gdView = (GridView)sender;
if (e.CommandName == "IDClick")
{
//Do something
}
}
private GridView getGridView()
{
GridView gdView = new GridView();
gdView.AutoGenerateColumns = false;
gdView.AutoGenerateSelectButton = true;
string name;
string[] field = ZGP.BLL.Search.getResultFormat(Convert.ToInt32(DDL_ResultView.SelectedValue), out name); //Ignore. This jst gets columnNames
if (field.Count() != 0)
{
gdView.Columns.Add(getSelectButton()); //Adds linkbutton
foreach (string cName in field) //ignore. This adds columns.
if (!String.IsNullOrEmpty(cName))
{
gdView.Columns.Add(GV_DataColumn.getGridViewColumn((DataColumnName)Enum.Parse(typeof(DataColumnName), cName))); //Ignore. adds columns
}
}
return gdView;
}
private ButtonField getSelectButton()
{
ButtonField _bf = new ButtonField();
_bf.ButtonType = ButtonType.Link;
_bf.HeaderText = "ID";
_bf.DataTextField = "ID";
_bf.CommandName = "IDClick";
return _bf;
}
Thanks for the help.
if (e.CommandName=="CommandName")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[index];
string boundFieldText= row.Cells[0].Text;
}
You'll need to create the grid view on each postback.

Categories