ASP C# CheckBox within DetailsView - c#

I have a DetailsView in my aspx page with two check boxes in item template columns. I have a buttoun outside DetailsView. What i need is when i click button it should verify whether both checkboxes are checked and fire c# command. please help. Let me paste Code below:
.aspx
<div>
<asp:Button ID="Button3" runat="server" Text="Button" OnClick="Button3_Click" />
</div>
<asp:DetailsView ID="DetailsView2" runat="server" Height="50px" Width="125px" AutoGenerateRows="False" DataSourceID="SqlDataSource2">
<Fields>
<asp:TemplateField HeaderText="StudentName" SortExpression="StudentName">
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:Label ID="Label1" runat="server" Text='<%# Bind("StudentName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email" SortExpression="Email">
<ItemTemplate>
<asp:CheckBox ID="CheckBox2" runat="server" />
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Email") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
C#
protected void Button3_Click(object sender, EventArgs e)
{
}

A DetailsView is a data bound control which can hold an unlimited number of rows, not just one.
If you want to verify both checkboxes are checked, in each row, you would need to iterate through all of the DetailsView's rows, and cast the CheckBox from FindControl on each row:
protected void Button3_Click(object sender, EventArgs e)
{
for (int i = 0; i < DetailsView2.Rows.Count; i++)
{
CheckBox chk1 = (CheckBox)DetailsView2.Rows[i].FindControl("CheckBox1");
CheckBox chk2 = (CheckBox)DetailsView2.Rows[i].FindControl("CheckBox2");
if (chk1.Checked && chk2.Checked)
{
// Do Stuff
}
}
}
If you want to verify all checkboxes are checkes in all rows, do this:
protected void Button3_Click(object sender, EventArgs e)
{
// Declare a boolean flag
bool AllCheckBoxesAreChecked = true;
for (int i = 0; i < DetailsView2.Rows.Count; i++)
{
CheckBox chk1 = (CheckBox)DetailsView2.Rows[i].FindControl("CheckBox1");
CheckBox chk2 = (CheckBox)DetailsView2.Rows[i].FindControl("CheckBox2");
if (!chk1.Checked || !chk2.Checked)
AllCheckBoxesAreChecked = false;
}
// Now use the flag
if (AllCheckBoxesAreChecked)
{
// Do Stuff
}
}

Related

Cannot find hidden input control on row data bound event

Here is my aspx file content.
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnUnload="UpdatePanel_Unload">
<ContentTemplate>
<table>
<tr>
<td>
<input id="hdnAID" type="hidden" runat="server" />
<asp:GridView ID="GridView1" runat="server" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDataBound="GridView1_RowDataBound" OnDataBound="GridView1_DataBound"
DataKeyNames="GeneralSettingID" EnableViewState="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<GridEditPopupMenu:GridEditPopupMenu ID="GridEditPopupMenu1" runat="server" currenttemplate="ItemTemplate" ShowDeleteLink="0" />
</ItemTemplate>
<EditItemTemplate>
<GridEditPopupMenu:GridEditPopupMenu ID="GridEditPopupMenu1" runat="server" currenttemplate="EditItemTemplate" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="GeneralSettingID" HeaderText="SettingNo" ReadOnly="true" />
<asp:TemplateField HeaderText="SettingName">
<ItemTemplate>
<asp:Label ID="Label25" runat="server" Text='<%# Eval("GeneralSettingName") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtUpdateGeneralSettingName" onfocus="this.blur();" runat="server" Text='<%# Bind("GeneralSettingName") %>'
Width="350px" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Values">
<ItemTemplate>
<asp:Label ID="Label23" runat="server" Text='<%# Eval("GeneralSettingValue") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtUpdateGeneralSettingValue" runat="server" Text='<%# Bind("GeneralSettingValue") %>'
Width="600px" TextMode="MultiLine" Rows="6" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Company1">
<ItemTemplate>
<asp:Label ID="Label28" runat="server" Text='<%# Eval("GeneralSettingCompany") %>' />
</ItemTemplate>
<ItemTemplate>
<asp:TextBox ID="txtUpdateGeneralSettingCompany" runat="server" Text='<%# Bind("GeneralSettingCompany") %>'
Width="100px" TextMode="MultiLine" Rows="1" Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Company2">
<ItemTemplate>
<asp:DropDownList ID="drpCompanyList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="drpCompanyList_SelectedIndexChanged" DataTextField="CompanyName" DataValueField="CompanyID"></asp:DropDownList>
<input id="hdnCompanyId" type="hidden" value='<%# Eval("GeneralSettingCompany") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
Here is the .cs side .
private LMSDataAccess.LookupsDataContext LkpDC = new LMSDataAccess.LookupsDataContext(ConfigFile.DBConnStr);
private System.Collections.Generic.List<LMSDataAccess.GeneralSetting> GeneralSettingList = null;
protected void Page_Load(object sender, EventArgs e)
{
base.ModuleID = 27;
if (!IsPostBack)
{
if (Request["AID"] != null)
hdnAID.Value = Request["AID"];
BindData();
}
}
private void BindData()
{
GeneralSettingList = LkpDC.GeneralSettingsGetAll(Common.NVLInt(hdnAID.Value),null).ToList();
GridView1.DataSource = GeneralSettingList;
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtUpdateGeneralSettingName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtUpdateGeneralSettingName");
TextBox txtUpdateGeneralSettingValue = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtUpdateGeneralSettingValue");
var hdnCompany = (HiddenField)GridView1.Rows[e.RowIndex].FindControl("hdnCompanyId") as HiddenField;
string KeyValue = GridView1.DataKeys[e.RowIndex].Value.ToString();
LkpDC.GeneralSettingsUpdate(Convert.ToInt32(KeyValue),
txtUpdateGeneralSettingName.Text,
txtUpdateGeneralSettingValue.Text,
Convert.ToInt32(hdnCompany.Value));
GridView1.EditIndex = -1;
BindData();
ResultCode = 0;
}
protected List<LMSDataAccess.Company> GetAllCompanies()
{
System.Collections.Generic.List<LMSDataAccess.Company> CompanyList = null;
LMSDataAccess.OrganizationDataContext OrgDC = new LMSDataAccess.OrganizationDataContext(ConfigFile.DBConnStr);
CompanyList = OrgDC.CompaniesGetAll(null).ToList();
return CompanyList;
}
protected void drpCompanyList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.Parent.Parent;
var hdnCompany = row.FindControl("hdnCompanyId") as HiddenField;
hdnCompany.Value = ddl.SelectedValue;
}
protected void GridView1_RowDataBound(object sender,GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var ddl = e.Row.FindControl("drpCompanyList") as DropDownList;
//here is the problem.
var hdn = e.Row.FindControl("hdnCompanyId") as HiddenField;
if (ddl != null)
{
ddl.DataSource = GetAllCompanies();
ddl.DataValueField = "CompanyID";
ddl.DataTextField = "CompanyName";
ddl.DataBind();
}
}
}
My beloved problem is not being able to get hdnCompanyId element when GridView1_RowDataBound and drpCompanyList_SelectedIndexChangedfired.I am always getting null.(as showed at the commented line )
I have tried under GridView1_RowDataBound event method like e.Row.FindControl("hdnCompanyId")
but it did not work.
My final aim is to setting and getting this element to control selected items of my dropdownlist.
I think the code is well written but I guess I am missing something about hierarchy of the user control elements.
Can you help me about what I am missing?
I have found that the problem was choosing the wrong casting type of the input.It must be HtmlInputHidden rather than HiddenField.I hope someone can get useful info from that question.

OnRowUpdating Does not take value of edit template textbox

I am trying to update a value in my gridview on row updating. However, it refuses to take in the value written in the textbox. I populate the gridview if the page is not post back. Help!
GRIDVIEW:
<asp:UpdatePanel runat="server" UpdateMode=Conditional><ContentTemplate>
<asp:GridView runat="server" ID="searchGV" AutoGenerateColumns="False" GridLines="None"
CssClass="mGrid" EmptyDataText="The Search Did Not Return Any Results"
PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt" Width="100%" OnRowCancelingEdit="searchGV_RowCancelingEdit"
OnRowEditing="searchGV_RowEditing" DataKeyNames="media_id" OnRowUpdating="searchGV_RowUpdating">
<Columns>
<asp:BoundField DataField="media_id" Visible="false" HeaderText="" />
<asp:BoundField DataField="dir_path" Visible="false" HeaderText="Dir" />
<asp:TemplateField HeaderText="Date Taken" >
<ItemTemplate>
<asp:LinkButton ID="dateLinkCsBtn" OnClientClick='<%#Eval("dir_path","Javascript:return test(\"{0}\",event);")%>'
runat="server" Text='<%# Bind("date") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Media Type">
<ItemTemplate>
<asp:Label runat="server" ID="mediaTypeLbl" Text='<%#Eval("description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Alias File Name">
<ItemTemplate>
<asp:Label runat="server" ID="aliasFileName" Text='<%#Bind("alias_file_name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" Text='<%#Bind("alias_file_name") %>' ID="updateAliasTxt"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
</asp:GridView>
</ContentTemplate></asp:UpdatePanel>
CODE BEHIND:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
FillGrid();
}
}
protected void searchGV_RowEditing(object sender, GridViewEditEventArgs e)
{
searchGV.EditIndex = e.NewEditIndex;
FillGrid();
}
protected void searchGV_RowCancelingEdit(object sender,
GridViewCancelEditEventArgs e)
{
searchGV.EditIndex = -1;
FillGrid();
}
public void FillGrid()
{
Media_DAO media_query = new Media_DAO();
searchGV.DataSource = media_query.get_search_media(alias_file_name_txt.Text.Trim(), Convert.ToInt16(mediaTypeDDL.SelectedValue),
from_date_txt.Text.Trim(), to_date_txt.Text.Trim(), Convert.ToInt16(Session["user_id"]));
searchGV.DataBind();
}
protected void searchGV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = searchGV.Rows[e.RowIndex];
TextBox new_alias = (TextBox)searchGV.Rows[e.RowIndex].FindControl("updateAliasTxt");
int media_id = Convert.ToInt16(searchGV.DataKeys[e.RowIndex]["media_id"]);
Media_DAO media_query2 = new Media_DAO();
media_query2.update_alias_name_by_id(media_id, new_alias.Text.Trim(), Convert.ToInt16(Session["user_id"]));
searchGV.EditIndex = -1;
FillGrid();
}
while declaring the grid you have specified only 1 *data key value*
asDataKeyNames="media_id"
DateKeys for grid view is stored in array format starting from 0.
The error may be in getting the media_id while updating. You need to change it as follows.
protected void searchGV_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = searchGV.Rows[e.RowIndex];
TextBox new_alias = (TextBox)searchGV.Rows[e.RowIndex].FindControl("updateAliasTxt");
int media_id = Convert.ToInt16(e.Keys[0]); //this will get the media_id
Media_DAO media_query2 = new Media_DAO();
media_query2.update_alias_name_by_id(media_id, new_alias.Text.Trim(), Convert.ToInt16(Session["user_id"]));
searchGV.EditIndex = -1;
FillGrid();
}
Since the earlier method was searchGV.DataKeys[e.RowIndex]["media_id"] , you might not get the media_id value if the row number which you are trying to edit is greater than 1.
The DataKeys property of GridView returns a collection of DataKey objects that represents the data key value of each row for a GridView. Thus, DataKeys[1] gives 2nd row, DataKeys[4] gives 5th row ...
Therefore, you need to use either the Value OR the Values property to access the value of a key field.
Rather than doing this:
int media_id = Convert.ToInt16(searchGV.DataKeys[e.RowIndex]["media_id"]);
do this:
int media_id = Convert.ToInt16(searchGV.DataKeys[e.RowIndex].Values["media_id"]);
// You can also use the Value property which gives the key value at index 0
int media_id = Convert.ToInt16(searchGV.DataKeys[e.RowIndex].Value);

GridView does not update values on postback?

I have a gridview with some custom templates:
<asp:GridView ID="gvGroups" runat="server" AutoGenerateColumns="False"
CssClass="table table-hover table-striped" GridLines="None" >
<Columns>
<asp:BoundField DataField="GroupDescription" HeaderText="Name" ReadOnly="True"
SortExpression="GroupDescription" />
<asp:TemplateField HeaderText="Administrator">
<ItemTemplate>
<asp:CheckBox ID="cbAdmin" runat="server"
Checked='<%# Boolean.Parse((Boolean)Eval("IsReadOnly") ? "True" : "False") ? false : true %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remove">
<ItemTemplate>
<asp:CheckBox ID="cbRemove" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" SortExpression="GroupID" Visible="False">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("GroupID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I then have a button that I click and that is supposed to change group administration and remove groups that are checked.
Here is the button code:
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gvGroups.Rows)
{
CheckBox cbAdmin = (CheckBox)gvr.FindControl("cbAdmin");
CheckBox cbRemove = (CheckBox)gvr.FindControl("cbRemove");
Label lblID = (Label)gvr.FindControl("lblID");
int id;
bool idValid = int.TryParse(lblID.Text,out id);
bool isReadOnly = !cbAdmin.Checked;
if (idValid)
{
Group g = SecurityManager.GetGroup(id);
if (g.IsReadOnly != isReadOnly)
{
bool updateSuccess = SecurityManager.ChangeGroupPermissions(id, isReadOnly);
}
if (cbRemove.Checked)
{
bool removeEmpSuccess = SecurityManager.RemoveEmployeesFromGroup(id);
bool removeSuccess = SecurityManager.RemoveGroup(id);
}
}
}
}
I used the debugger and even when I uncheck admin on all groups, when I look at cbAdmin.Checked, it is still true, which is the same value it started with, thus nothing ever happens.
What could be the problem? Why am I not seeing the updated values on the button postback?
Thanks
You have to call GridView#DataBind() within if(!IsPostBack){ }
Also you need to set AutoPostBack property of the textboxes to "true"
I guess that you're databinding the GridView on postbacks. That will load the data from database again and prevent changes. So ue the PostBack property of the Page:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
DataBindGridView();
}
}

GridView into UpdatePanel fires OnRowUpdating event : but I can see only the controls inside ItemTemplate instead of EditItemTemplate?

As i was written in the title, the problem is very funny :
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id_Newsletter" HeaderStyle-BackColor="Black"
HeaderStyle-ForeColor="White" RowStyle-BackColor="DarkGray" AlternatingRowStyle-BackColor="LightGray" PageSize="6" AllowPaging="true"
AllowSorting="true" ShowHeaderWhenEmpty="true" EmptyDataText="La tabella non contiene dati" EnableViewState="true" RowStyle-Wrap="true"
PagerStyle-HorizontalAlign="Left" PagerStyle-BorderWidth="0" BorderWidth="0" OnRowCommand="GridView_RowCommand"
OnRowCancelingEdit="GridView_RowCancelingEdit" OnRowUpdating="GridView_RowUpdating" OnRowDeleting="GridView_RowDeleting"
OnPageIndexChanging="GridView_PageIndexChanging" OnSorting="GridView_Sorting" OnRowEditing="GridView_RowEditing" CssClass="NewsletterManager_GridView" >
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Indirizzo Email" HeaderStyle-Width="275" SortExpression="emailNewsletter">
<ItemTemplate>
<asp:Label ID="lbl_emailNewsletter" runat="server" Text='<%# Eval("emailNewsletter") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lbl_emailNewsletter" runat="server" Text='<%# Eval("emailNewsletter") %>' Visible="false" ></asp:Label>
<asp:TextBox ID="txt_emailNewsletter" runat="server" Text='<%# Bind("emailNewsletter") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Azioni" HeaderStyle-Width="100">
<EditItemTemplate>
<asp:ImageButton ID="Img_Aggiorna" runat="server" CommandName="Update" ImageUrl="~/images/GridIcon/update.png" ToolTip="Aggiorna" />
<asp:ImageButton ID="Img_Annulla" runat="server" CommandName="Cancel" ImageUrl="~/images/GridIcon/undo.png" ToolTip="Annulla" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="Img_Modifica" runat="server" CommandName="Edit" ImageUrl="~/images/GridIcon/edit.png" ToolTip="Modifica" />
<asp:ImageButton ID="Img_Cancella" runat="server" CommandName="Delete" ImageUrl="~/images/GridIcon/delete.png" OnClientClick="return confirm('Sei sicuro di voler cancellare l\'email?');" ToolTip="cancella" />
</ItemTemplate>
</asp:TemplateField>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
LoadGridView(GridView1, -1, 0);
lbl_result.Text = String.Empty;
}
protected void GridView_RowEditing(Object sender, GridViewEditEventArgs e)
{
LoadGridView(((GridView)sender), e.NewEditIndex, ((GridView)sender).PageIndex);
}
protected void GridView_RowUpdating(Object sender, GridViewUpdateEventArgs e)
{
NewsLetterBL newsBl = new NewsLetterBL();
String oldmail = ((Label)((GridView)sender).Rows[e.RowIndex].FindControl("lbl_emailNewsletter")).Text;
String newmail = ((TextBox)((GridView)sender).Rows[e.RowIndex].FindControl("txt_emailNewsletter")).Text;
if (newsBl.ModifyWrongEmail(oldmail, newmail))
lbl_result.Text = "Modify Done";
else lbl_result.Text = newsBl.LastMessage;
LoadGridView(((GridView)sender), -1, ((GridView)sender).PageIndex);
}
protected void LoadGridView(GridView GV, int EditIndex, int PageIndex)
{
NewsLetterBL newsBl = new NewsLetterBL();
DataView dw = new DataView(newsBl.getFullNewsletter());
String SortExpression = GV.ID.ToString() + "_SortExpression";
if (ViewState[SortExpression] != null) dw.Sort = (String)ViewState[SortExpression];
GV.DataSource = dw;
GV.PageIndex = PageIndex;
GV.EditIndex = EditIndex;
GV.DataBind();
}
When I try to access to the txt_emailNewsletter control into the row in edit mode from the GridView_RowUpdating that handle the OnRowUpdating event of the GridView1, the element throws a NullReferenceException, but the lbl_emailNewsletter control can be founded.
The labels into ItemTemplate and EditItemTemplate have the same ID (lbl_emailNewsletter): if I change the ID of the label into the ItemTemplate, both the String oldmail and newmail throws an exception of null Reference ; clearly the problem is that when I click on ImageButton Img_Aggiorna with CommandName="Update", ASP.NET for a mysterious reason Find only controls of ItemTemplate instead of EditItemTemplate from the edited row.
GridView event "OnRowUpdating" is useful only if you use a datasource : in this case is possible to access to the Dictionary e.OldValues[] or e.NewValues[] and get correctly the old and new values.
I have solved the problem using the event "OnRowCommand" with a personalized CommandName and a CommandArgument with the old values : in this case is possible to access to all the controls inside the edited row in the GridView with the new values.
<asp:ImageButton ID="Img_Update" runat="server" CommandName="Change" CommandArgument='<%# Eval("emailNewsletter") %>' ImageUrl="~/images/GridIcon/update.png" ToolTip="Update" />
protected void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "Change":
ImageButton btnNew = e.CommandSource as ImageButton;
GridViewRow row = btnNew.NamingContainer as GridViewRow;
TextBox txt_emailNewsletter = row.FindControl("txt_emailNewsletter") as TextBox;
if ( !CheckEmail(e.CommandArgument.ToString()) || !CheckEmail(txt_emailNewsletter.Text) )
lbl_result.Text = "ERROR : Email not Valid";
else {
if (txt_emailNewsletter.Text.Trim().ToLower() == e.CommandArgument.ToString())
lbl_result.Text = "Email values are indentical";
else
{
//Business Layer Call
NewsLetterBL newsBl2 = new NewsLetterBL();
if (newsBl2.ModifyWrongEmail(e.CommandArgument.ToString(), txt_emailNewsletter.Text.Trim().ToLower()))
lbl_result.Text = "Email Changed";
else
lbl_result.Text = "ERROR : " + newsBl2.LastMessage;
}
}
LoadDataForGridView(((GridView)sender));
BindGridView(((GridView)sender), -1, ((GridView)sender).PageIndex);
break;
}
}

Find out a CHECKBOX in a DATAGRID in ASP.NET

I have a GRIDVIEW and with several CHECKBOXS.
When i selected a CHECKBOX I need run some code.
To detect it, I use an EVENT HANDLER for the CHECKBOX included in a GRIDVIEW.
I cannot access the CHECKBOX with my wrong code.
Do you have any idea what I am doing wrong? Thanks for your help. Bye
ASPX
<asp:Label ID="uxMessageDisplayer" runat="server" Visible="False" EnableViewState="False"></asp:Label>
<asp:GridView ID="uxUserListDisplayer" runat="server" AutoGenerateColumns="False"
OnRowDataBound="uxUserListDisplayer_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
<asp:CheckBox ID="uxActiveCheckBoxSelector" runat="server" AutoPostBack="true" OnCheckedChanged="uxRoleCheckBoxSelector_CheckChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Users">
<ItemTemplate>
<asp:Label runat="server" ID="uxUserNameLabelDisplayer" Text='<%# Container.DataItem %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="uxLinkEditButton" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="uxLinkDeleteButton" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CODE BEHIND
protected void uxRoleCheckBoxSelector_CheckChanged(object sender, EventArgs e)
{
// Reference the CheckBox that raised this event
//CheckBox uxActiveCheckBoxSelector = sender as CheckBox;
CheckBox activeCheckBox = (CheckBox)FindControl("uxActiveCheckBoxSelector");
if (activeCheckBox.Checked == true)
{
uxMessageDisplayer.Text = "T - Aproved User";
uxMessageDisplayer.Enabled = false;
}
else
{
uxMessageDisplayer.Text = "F - NOT Aproved User";
uxMessageDisplayer.Enabled = false;
}
}
If I am not mistaken by your question, you are trying to set the text of the label on the same row with the checkbox based on its checked status.
Below is the code snippet I tried on my pc, hope it helps.
.aspx:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
return;
//create dummy data
List<string> rows = new List<string>();
Enumerable.Range(1, 5).ToList().ForEach(x => rows.Add(x.ToString()));
//bind dummy data to gridview
GridView1.DataSource = rows;
GridView1.DataBind();
}
protected void CheckBox1_CheckChanged(object sender, EventArgs e)
{
//cast sender to checkbox
CheckBox CheckBox1 = (CheckBox)sender;
//retrieve the row where checkbox is contained
GridViewRow row = (GridViewRow)CheckBox1.NamingContainer;
//find the label in the same row
Label Label1 = (Label)row.FindControl("Label1");
//logics
if (CheckBox1 != null) //make sure checkbox1 is found
{
if (CheckBox1.Checked)
{
if (Label1 != null) //make sure label1 is found
{
Label1.Text = "Checked";
}
}
else
{
if (Label1 != null)
{
Label1.Text = "Unchecked";
}
}
}
}
I'm assuming the event handler is actually registered to the checkbox.
CheckBox activeCheckBox = (CheckBox)sender;
what is "uxActiveCheckBoxSelector" and why are you ignoring sender?
Code corrected as suggest!
Usefull resource for beginners
protected void uxRoleCheckBoxSelector_CheckChanged(object sender, EventArgs e)
{
// Cast sender to CheckBox
CheckBox activeCheckBox = (CheckBox)sender;
// Retrieve the row where CheckBox is contained (NamingContainer used to retrive parent control
GridViewRow row = (GridViewRow)activeCheckBox.NamingContainer;
if (activeCheckBox.Checked == true)
{
uxMessageDisplayer.Text = "T - Aproved User";
}
else
{
uxMessageDisplayer.Text = "F - NOT Aproved User";
}
}

Categories

Resources