Preserving CheckBox's Value in Dynamic GridView TemplateField - asp.net

I am trying to create a GridView which will contain a list of users and permission levels that they have access to. Each row will have the following fields: User_ID, Username, Permission1, Permission2, ..., PermissionN, where the values of permissions field are "0" if the user does not have that permission and "1" if they do (note that columns returned by the DAL are not named Permission1, but rather are the actual name of the permission). I would like to represent the data by using CheckBoxes, to allow an admin to quickly grant or revoke permissions to a large number of users at once.
Since I will not know the number of permissions before-hand, I dynamically create TemplateFields and CheckBoxes, and this works fine; the GridView shows the current permission levels of all the users. I run into a problem when I try to update permissions based on the user checking and unchecking boxes.
Once the user is done changing permissions, I have an "Update" button, which of course causes a postback. Since the postback occurs before the OnClick event, by the time I reach OnClick all of the CheckBoxes have been reset to their initial values. Is there a way I can somehow grab the value of the CheckBoxes' Checked property before the postback occurs? Is there another (better) way of doing this? Thanks.
ASPX:
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False"
EnableModelValidation="True" DataKeyNames="ID">
</asp:GridView>
<asp:ObjectDataSource ID="odsUsers" runat="server" SelectMethod="GET_USERS"
TypeName="oDAL">
</asp:ObjectDataSource>
<asp:Button ID="btnUpdate" runat="server" Text="Update Permissions" OnClick="btnUpdate_OnClick"/>
Code Behind:
private static string[] excludeCols = { "ID", "Username" };
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) // Removing the IsPostBack check refreshes the GridView when the Update button is clicked
bindGridViewWithHiddenID(gvUsers, ((DataView)odsUsers.Select()).Table, excludeCols);
}
public static bool bindGridViewWithHiddenID(GridView gv, DataTable dt, string[] excludeCols)
{
gv.Columns.Clear();
gv.DataBind();
if (gv != null && dt != null && dt.Rows.Count > 0)
{
DataControlField newField;
foreach (DataColumn column in dt.Columns)
{
if (excludeCols.Contains(column.ColumnName))
{
newField = new BoundField();
((BoundField)newField).DataField = column.ColumnName;
}
else
{
newField = new TemplateField();
((TemplateField)newField).ItemTemplate = new CustomTemplate(column.ColumnName);
}
newField.HeaderText = column.ColumnName;
if (column.ColumnName == "ID" || column.ColumnName.EndsWith("_ID"))
newField.Visible = false;
gv.Columns.Add(newField);
}
gv.DataSource = dt;
gv.DataBind();
return true;
}
return false;
}
// By this time execution reaches here the CheckBoxes have already been reset
protected void btnUpdate_Click(object sender, EventArgs e)
{
...
}
CustomTemplate class:
public class CustomTemplate : ITemplate
{
private string binding;
private static int count = 0;
public CustomTemplate(string colNameBinding)
{
binding = colNameBinding;
}
public void InstantiateIn(Control container)
{
CheckBox chk = new CheckBox();
chk.ID = "chk" + count++;
chk.DataBinding += new EventHandler(this.chk_OnDataBinding);
container.Controls.Add(chk);
}
public void chk_OnDataBinding(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
GridViewRow namingContainer = (GridViewRow)chk.NamingContainer;
DataRowView dataRow = (DataRowView)namingContainer.DataItem;
if (dataRow[binding].ToString() == "1")
chk.Checked = true;
else
chk.Checked = false;
}

This behavior is expected and is normal. It has to do with the Page Life cycle and tracking of ViewState on dynamically added controls. I recommend you read this article from Scott Mitchell, specially the section titled: View State and Dynamically Added Controls.

I tried adding the GridView binding to OnInit() but since the CheckBoxes aren't actually instantiated until the GridView is DataBound, and since DataBinding will revert the GridView back to its original state, I seem to be stuck again.

Related

dropdownchanged event not firing in usercontrol in asp.net

I have a dropdownlist in a usercontrol as shown below
<asp:dropdownlist id="ddlLanguage" runat="server" AutoPostBack="true" EnableViewState="true" onselectedindexchanged="ddlLanguage_SelectedIndexChanged">
</asp:dropdownlist>
my selectedchanged event is not getting fired even once
in code behind
if (!IsPostBack)
{
//dt - is list of languages availbale in DB
//value[0]-contains lang currently to be binded to dropdownlist based
//remaining values (values [1]) to are to be populated to textbox
LoadModuleInfo(dt,values)
}
private void LoadModuleInfo(System.Data.DataTable dtLanguages, string[] values)
{
this.txbxModuleName.Text = values[1];
this.ddlLanguage.DataSource = dtLanguages;
this.ddlLanguage.DataTextField = "language_description";
this.ddlLanguage.DataValueField = "language";
this.ddlLanguage.DataBind();
// set up selections on the screen
this.ddlLanguage.SelectedIndex = this.getIndex(dtLanguages, values[0]);
}
protected void ddlLanguage_SelectedIndexChanged(object sender, System.EventArgs e)
{
//get new values ( values[0] and values[1])
LoadModuleInfo(dtLanguages, values);
}
protected int getIndex(DataTable dt, string recordId)
{
int intCt = 0;
foreach (System.Data.DataRow dr in dt.Rows)
{
if (dr[0].ToString() == recordId)
{
break;
}
else
{
intCt++;
}
}
return intCt;
}
i have wriiten the above code, but selectedchanged event is not fired for dropdownlist control available in USERCONTROL.
Please help.
If you page not refreshed at all .. most probably you have a javascript error in the page
Kindly remove below line from your code and try
this.ddlLanguage.DataValueField = "language";
or
change this too language to language_description

Creating dynamic controls in Page_PreRender based on viewstate causes button OnClick event to not work

I realize that dynamic controls should be created within Page_Load and Page_Init in order for them to be registered in the control tree.
I have created a custom control that requires the use of ViewState in a button OnClick event. This ViewState is then used to dynamically create controls.
Since the life-cycle will go: Page Load -> Button Click -> Page PreRender. The view-state will not be updated until "Button Click", thus I am creating my dynamic controls in Page PreRender. However, creating a button and programatically assigning the OnClick EventHandler in Page_PreRender does not work.
Does anyone know how I can get this to work?
btn_DeleteTableRow_Click will not fire. This is setup in CreatePartRows()
Here is my example:
<asp:UpdatePanel ID="up_RMAPart" runat="server" UpdateMode="Conditional" EnableViewState="true" ChildrenAsTriggers="true">
<ContentTemplate>
<div class="button" style="width: 54px; margin: 0px; float: right;">
<asp:Button ID="btn_AddPart" runat="server" Text="Add" OnClick="btn_AddPart_Click" />
</div>
<asp:Table ID="Table_Parts" runat="server" CssClass="hor-zebra">
</asp:Table>
<div class="clear"></div>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btn_AddPart" EventName="Click" />
</Triggers>
Code Behind:
[Serializable]
public struct Part
{
public string PartName;
public int Quantity;
public int PartID;
public Part(string sPartName, int iQuantity, int iPartID)
{
PartName = sPartName;
Quantity = iQuantity;
PartID = iPartID;
}
}
public partial class RMAPart : System.Web.UI.UserControl
{
private Dictionary<string,Part> m_RMAParts;
private int m_RowNumber = 0;
public Dictionary<string, Part> RMAParts
{
get
{
if (ViewState["m_RMAParts"] != null)
return (Dictionary<string, Part>)ViewState["m_RMAParts"];
else
return null;
}
set
{
ViewState["m_RMAParts"] = value;
}
}
public int RowNumber
{
get
{
if (ViewState["m_RowNumber"] != null)
return Convert.ToInt32(ViewState["m_RowNumber"]);
else
return 0;
}
set
{
ViewState["m_RowNumber"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
RMAParts = new Dictionary<string, Part>();
RowNumber = 0;
RMAParts.Add("PartRow_" + RowNumber.ToString(), new Part());
RowNumber = 1;
CreatePartRows();
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
CreatePartRows();
}
private void CreatePartRows()
{
Table_Parts.Controls.Clear();
TableHeaderRow thr = new TableHeaderRow();
TableHeaderCell thc1 = new TableHeaderCell();
thc1.Controls.Add(new LiteralControl("Part"));
thr.Cells.Add(thc1);
TableHeaderCell thc2 = new TableHeaderCell();
thc2.Controls.Add(new LiteralControl("Quantity"));
thr.Cells.Add(thc2);
TableHeaderCell thc3 = new TableHeaderCell();
thc3.Controls.Add(new LiteralControl(""));
thr.Cells.Add(thc3);
Table_Parts.Rows.Add(thr);
foreach (KeyValuePair<string, Part> kvp in RMAParts)
{
string[] sKey = kvp.Key.Split('_');
TableRow tr = new TableRow();
tr.ID = kvp.Key;
TableCell tc1 = new TableCell();
TextBox tb_Part = new TextBox();
tb_Part.ID = "tb_Part_" + sKey[1];
tb_Part.CssClass = "textbox1";
tc1.Controls.Add(tb_Part);
tr.Cells.Add(tc1);
TableCell tc2 = new TableCell();
TextBox tb_Quantity = new TextBox();
tb_Quantity.ID = "tb_Quanitty_" + sKey[1];
tb_Quantity.CssClass = "textbox1";
tc2.Controls.Add(tb_Quantity);
tr.Cells.Add(tc2);
TableCell tc3 = new TableCell();
Button btn_Delete = new Button();
btn_Delete.ID = "btn_Delete_" + sKey[1];
btn_Delete.CommandArgument = tr.ID;
btn_Delete.Click += new EventHandler(btn_DeleteTableRow_Click);
btn_Delete.Text = "Remove";
tc3.Controls.Add(btn_Delete);
tr.Cells.Add(tc3);
Table_Parts.Rows.Add(tr);
}
}
public void Reset()
{
Table_Parts.Controls.Clear();
RMAParts.Clear();
RowNumber = 0;
RMAParts.Add("PartRow_" + RowNumber.ToString(), new Part());
RowNumber = 1;
CreatePartRows();
}
protected void btn_AddPart_Click(object sender, EventArgs e)
{
RMAParts.Add("PartRow_" + RowNumber.ToString(), new Part());
RowNumber++;
}
protected void btn_DeleteTableRow_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
TableRow tr = (TableRow)Table_Parts.FindControl(btn.CommandArgument);
Table_Parts.Rows.Remove(tr);
RMAParts.Remove(btn.CommandArgument);
}
}
To ensure that the values of input fields persist across postbacks and that server events are raised:
Use view state to keep track of dynamically created controls.
Re-create the controls with the same IDs in LoadViewState (not Load or PreRender, because then the values of input fields will be lost).
The rest of this answer details how I modified your code to get it to work.
RMAPart.ascx
Just for convenience, you can declare the header row in the .ascx:
<asp:Table ID="Table_Parts" runat="server" CssClass="hor-zebra">
<asp:TableRow>
<asp:TableHeaderCell Text="Part" />
<asp:TableHeaderCell Text="Quantity" />
<asp:TableHeaderCell />
</asp:TableRow>
</asp:Table>
RMAPart.ascx.cs
To keep track of dynamically created rows, maintain a list of row IDs in view state:
public partial class RMAPart : System.Web.UI.UserControl
{
private List<string> RowIDs
{
get { return (List<string>)ViewState["m_RowIDs"]; }
set { ViewState["m_RowIDs"] = value; }
}
In the btn_AddPart_Click handler, generate a new row ID and create the controls for the new row:
protected void btn_AddPart_Click(object sender, EventArgs e)
{
string id = GenerateRowID();
RowIDs.Add(id);
CreatePartRow(id);
}
private string GenerateRowID()
{
int id = (int)ViewState["m_NextRowID"];
ViewState["m_NextRowID"] = id + 1;
return id.ToString();
}
private void CreatePartRow(string id)
{
TableRow tr = new TableRow();
tr.ID = id;
TableCell tc1 = new TableCell();
TextBox tb_Part = new TextBox();
tb_Part.ID = "tb_Part_" + id;
tb_Part.CssClass = "textbox1";
tc1.Controls.Add(tb_Part);
tr.Cells.Add(tc1);
TableCell tc2 = new TableCell();
TextBox tb_Quantity = new TextBox();
tb_Quantity.ID = "tb_Quantity_" + id;
tb_Quantity.CssClass = "textbox1";
tc2.Controls.Add(tb_Quantity);
tr.Cells.Add(tc2);
TableCell tc3 = new TableCell();
Button btn_Delete = new Button();
btn_Delete.ID = "btn_Delete_" + id;
btn_Delete.CommandArgument = id;
btn_Delete.Click += btn_DeleteTableRow_Click;
btn_Delete.Text = "Remove";
tc3.Controls.Add(btn_Delete);
tr.Cells.Add(tc3);
Table_Parts.Rows.Add(tr);
}
In the btn_DeleteTableRow_Click handler, delete the clicked row and update view state:
protected void btn_DeleteTableRow_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
TableRow tr = (TableRow)Table_Parts.FindControl(btn.CommandArgument);
Table_Parts.Rows.Remove(tr);
RowIDs.Remove(btn.CommandArgument);
}
Hook Page_Load and start things off by creating the first row:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Reset();
}
}
public void Reset()
{
while (Table_Parts.Rows.Count > 1)
Table_Parts.Rows.RemoveAt(Table_Parts.Rows.Count - 1);
ViewState["m_NextRowID"] = 0;
string id = GenerateRowID();
RowIDs = new List<string> { id };
CreatePartRow(id);
}
Override LoadViewState and re-create the rows using the IDs stored in view state:
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
foreach (string id in RowIDs)
{
CreatePartRow(id);
}
}
}
Dealing with Parts
The code above doesn't use your Part structure at all. To actually move data between your business objects and the user control, you can add a public method that takes a Part collection and uses it to create rows and populate text boxes, and then add another public method that reads out the values of the text boxes into a Part collection.
The button click isn't being fired because control events are called right after the Load event. Your button isn't in the control hierarchy at the time that the asp.net lifecycle is trying to call your event, so it's being dropped. Remember, it's a round-trip and the control has to exist on postback before the LoadComplete event fires for its event handlers to get called.
Create your dynamic controls in the PreLoad or Load event and you should be OK (you will have access to the full viewstate at that time to make any decisions regarding whether or not you need to dynamically create your delete button for that row).
ASP.net Page Lifecycle Docs: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx
I think that Robert has the right answer, but needs to be more clear about WHICH Page.Load he is talking about. There are three page requests here.
Initial Page request, no initial button click yet.
Postback on button click. No processing in Page Load. PreRender call creates the new table rows and the new button and links up the button click event to the new button.
Postback after the client clicks on the new button. You need to re-create the dynamic button in Page Load so that the Click event of the dynamic button doesn't get dropped.
Agree with Robert and Bill.
But to add here, in my opinion only way that you would achieve this is by creating a custom control/web server control (inheriting WebControl class), where you override the CreateChildControls method and RenderContents methods. I think this is what you mean when you said, in one of your comments, you are going to code out a grid-view version.

Unable to FindControl() in ListView ItemEditing

I have a ListView in an ASP.NET web application. When a user clicks the edit button, I want textfields to pop up that are dependent on certain values of the item. However, I can't seem to find any controls inside of my ListView1_ItemEditing() function.
I have read the Microsoft documentation and various help threads on the internet, but their suggestions do not appear to work for me. This is generally what I see:
ListViewItem item = ProductsListView.Items[e.NewEditIndex];
Label dateLabel = (Label)item.FindControl("DiscontinuedDateLabel");
For the sake of simplicity I just want to be able to select a label in ListView1_ItemEditing(). This is the code in ListView1_ItemEditing():
protected void ListView1_ItemEditing(Object sender, ListViewEditEventArgs e)
{
DataBind(); //not sure if this does anything
ListViewItem item = ListView1.Items[e.NewEditIndex];
Label debugLabel = (Label)item.FindControl("label_editing");
debugLabel.Text = "Works";
}
Here is the ASP
<EditItemTemplate>
<asp:Label ID="label_editing" runat="server" Text="hello world"></asp:Label>
</EditItemTemplate>
When debugging, item and debugLabel are both NULL.
UPDATE: I resolved this issue by moving my logic to ItemDataBound and then checking if my tr (containing textboxes) was in that particular data item. Code below:
protected void ListView1_ItemDataBound(object sender, ListViewItemEventArgs e)
{
if (e.Item.ItemType == ListViewItemType.DataItem)
{
Control tr_verizon = e.Item.FindControl("tr_verizonEdit");
Control tr_att = e.Item.FindControl("tr_attEdit");
if (tr_verizon != null)
{
//Control tb_meid = e.Item.FindControl("TextBox_Meid");
Label lbl_carrierId = (Label)e.Item.FindControl("lbl_carrierId");
if (lbl_carrierId == null)
{
Message.Text = "lbl_carrierId is null!";
}
else if (lbl_carrierId.Text.Equals(""))
{
Message.Text = "lbl_carrierId is empty!";
}
else
{
string recordId = lbl_carrierId.Text;
if (tr_verizon != null && tr_att != null)
{
if (lbl_carrierId.Text.Equals("1"))
{
tr_verizon.Visible = false;
tr_att.Visible = true;
}
else
{
tr_verizon.Visible = true;
tr_att.Visible = false;
}
}
}
}
}
}
The ItemEditing event is raised when an item's Edit button is clicked, but before the ListView item is put in edit mode. Therefore controls in EditItemTemplate are not available at this time.
More Info and example
You should do the DataBind() first, like this:
ListView1.EditIndex = e.NewEditIndex;
ListView1_BindData(); // a function that get the DataSource and then ListView1.DataBind()
// Now find the control as you did before
Have you tried casting the sender object instead of trying to access your ListViewItem by index?
protected void ListView1_ItemEditing(Object sender, ListViewEditEventArgs e)
{
var item = sender as ListViewItem;
var debugLabel = item.FindControl("label_editing") as Label;
debugLabel.Text = "Works";
}

ASPxCombobox not fetched from SQLdatasource saved in session

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (Session["SavedSQLSources"] == null)
SavedSQLSources = new Dictionary<String, SqlDataSource>();
SavedSQLSources.Add(ASPxComboBox1.ID, SqlDataSource1);
SavedSQLSources.Add(ASPxComboBox2.ID, SqlDataSource2);
Session["SavedSQLSources"] = SavedSQLSources;
}
else
{
if (Session["SavedSQLSources"] != null)
SavedSQLSources = (Dictionary<String, SqlDataSource>)Session["SavedSQLSources"];
}
}
Greetings, I have multiple ASPxCombobox with each having their own datasource. So first I saved
each control ID with their corresponding datasource object in a dictionary.
protected void Cmb_Callback(object source, CallbackEventArgsBase e)
{
ASPxComboBox comboBox = (ASPxComboBox)source;
string[] args = e.Parameter.Split('|');
for (int i = 0; i < args.Length; ++i)
SavedSQLSources[comboBox.ID].SelectParameters[i].DefaultValue = args[i];
comboBox.DataSourceID = SavedSQLSources[comboBox.ID].ID;
comboBox.DataBind();
}
Doing a few actions on the page, each control then launch its callback and bind its data with the corresponding datasource.
Well... Work perfectly when using directly the datasource, but having no items fetched when it's from a datasource saved in Session (from SavedSQLSources).
Shouldn't the instance of the object be the same ?
Thanks in advance, TheRainFall.
Ok, I gave up on the dictionnary method and resolved this by linking each ASPxCombobox to its SqlDatasource from client-side:
DataSourceID="SqlDataSource1"
Then in the callback I got the sqldatasource instance from the parent container by using the datasourceID referenced from client-side:
SqlDataSource tempSqlDatasource= (SqlDataSource)comboBox.Parent.FindControl(comboBox.DataSourceID);
The main purpose was to reload all combobox without reloading the page although I could have done this client-side only.

Event problem inside grid view with custom paging

I want to provide custom paging in grid view.
<asp:GridView ID="gvFirst" runat="server" AutoGenerateColumns="false"
AllowPaging="true"
ondatabound="gvFirst_DataBound" >
<Columns>
<asp:BoundField DataField="ID" HeaderText="ProductID"/>
<asp:BoundField DataField="Name" HeaderText="ProductName" />
</Columns>
<PagerTemplate>
<asp:Panel ID="pnlPager" runat="server">
</asp:Panel>
</PagerTemplate>
</asp:GridView>
If I create button here and bind click event then it is fire, but problem is this event occur for each row bind with grid
protected void gvFirst_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Pager)
{
Panel pnPager = e.Row.FindControl("pnlPager") as Panel;
if (pnPager != null)
{
Button btnFirst = new Button();
btnFirst.Text = "1";
btnFirst.Click += new EventHandler(btnFirst_Click);
pnPager.Controls.Add(btnFirst);
}
}
}
If I create button here and bind click event then it is not fire; this event fire after all the rows bind to grid, so it will occur only once.
protected void gvFirst_DataBound(object sender, EventArgs e)
{
GridViewRow gvRow = gvFirst.BottomPagerRow;
if (gvRow != null)
{
Panel pnPager = gvRow.FindControl("pnlPager") as Panel;
if (pnPager != null)
{
Button btnFirst = new Button();
btnFirst.Text = "1";
btnFirst.Click += new EventHandler(btnFirst_Click);
pnPager.Controls.Add(btnFirst);
}
}
}
void btnFirst_Click(object sender, EventArgs e)
{
using (_NorthWindDataContext = new NorthWindDataContext())
{
var ProductInformation = from p in _NorthWindDataContext.Products
select new
{
ID = p.ProductID,
Name = p.ProductName
};
gvFirst.DataSource = ProductInformation.Skip(5).Take(5);
gvFirst.DataBind();
}
}
Another problem which I am facing is I want to provide custom paging. Now I have set page size to 5 and I am fetching 5 record from query so my grid pager is not display.
public class Productinformation
{
public int PID
{
get;
set;
}
public string PName
{
get;
set;
}
}
using (NorthWindDataContext _NorthWindDataContext = new NorthWindDataContext())
{
Proinfo = new List<Productinformation>();
Proinfo = (from p in _NorthWindDataContext.Products
select new Productinformation
{
PID = p.ProductID,
PName = p.ProductName,
}).ToList();
gvFirst.DataSource = Proinfo.Take(PageSize) ;
gvFirst.DataBind();
}
Proinfo variable declare globally.
Now when I bind I run this code it will give me error the data source does not support server-side data paging. If I use var type of variable then it is worked but we can't declare var type of variable globally, so I used it then I have to call this method every time in paging, and I don't want to use Objectdatasource.
GridView's RowCreated indeed will be called for every row in GridView, because that is the event where the GridView will (re)create the GridViewRows. But if you check for if (e.Row.RowType == DataControlRowType.Pager) there will be no overhead. This event is perfect for creating dynamic controls because it's called even on postback(as against RowDataBound). So your first way should be the correct one.
If you want to show the pager also when there are less than PageSize rows, you should force the pager to be visible e.g. in GridView's overridden OnPreRender.
GridViewRow pagerRow = (GridViewRow) this.BottomPagerRow;
if(pagerRow != null) pagerRow.Visible = true;

Resources