Get value from gridview footer in tab control - c#

I've got a tab control with a gridview in it. I want to add new records using the footer row but when I try and save the record, I can't find the value in the textbox. I've set the clientidmode = static, I've also tried using a recursive findcontrol but to no avail. Please can someone help
Thanks
<asp:UpdatePanel ID="pnl" runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:TabContainer ID="TabDetails" runat="server" AutoPostBack="true" OnActiveTabChanged="TabDetails_ActiveTabChanged"
ActiveTabIndex="1">
<asp:TabPanel runat="server" ID="TabNotes" HeaderText="Notes" CssClass="tabinactive">
<ContentTemplate>
<asp:GridView ID="GrdNotes" ClientIDMode="Static" runat="server" AutoGenerateColumns="false"
Width="99%" OnRowEditing="GrdNotes_RowEditing" OnRowCancelingEdit="GrdNotes_RowCancelingEdit"
OnRowUpdating="GrdNotes_RowUpdating" OnRowDeleting="GrdNotes_RowDeleting" OnRowCreated="GrdNotes_RowCreated"
ShowFooter="false">
<Columns>
<asp:TemplateField HeaderText="Notes">
<ItemTemplate>
<asp:HiddenField ID="hfNotesID" runat="server" Value='<%# Bind("Notes_ID")%>' />
<asp:Label ID="LblNotes" runat="server" Text='<%# Bind("Notes")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TxtNotes" runat="server" Text='<%# Bind("Notes")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TxtNewNotes" ClientIDMode="Static" runat="server" Width="300px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Notes_Date" ReadOnly="True" DataFormatString="{0:dd/MM/yyyy}"
HeaderText="Date" />
<asp:BoundField DataField="FullName" ReadOnly="True" HeaderText="Entered By" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnAdd" runat="server" Text="Add Notes" OnClick="btnAddVisitNotes_Click" />
</ContentTemplate>
</asp:TabPanel>
</asp:TabContainer>
</ContentTemplate>
</asp:UpdatePanel>
private void BindNotes(int id)
{
var qry = from vn in dc.sp_list_notes(id)
orderby vn.Notes_Date descending
select vn;
GrdNotes.DataSource = qry.ToList();
GrdNotes.DataBind();
}
protected void GrdNotes_RowCreated(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
var lnk = new LinkButton();
lnk.Text = "Save";
lnk.ID = "btnAddNotesSave";
lnk.CausesValidation = false;
lnk.Command += new CommandEventHandler(btnAddNotesSave_Click);
lnk.CssClass = "norm";
e.Row.Cells[1].Controls.Add(lnk);
var lbl = new Label();
lbl.Text = "XX";
lbl.ID = "LblSpace";
lbl.CssClass = "norm_w";
e.Row.Cells[1].Controls.Add(lbl);
var lnk1 = new LinkButton();
lnk1.Text = "Cancel";
lnk1.ID = "btnAddNotesCancel";
lnk1.CausesValidation = false;
lnk1.Command += new CommandEventHandler(btnAddNotesCancel_Click);
lnk1.CssClass = "norm";
e.Row.Cells[1].Controls.Add(lnk1);
}
protected void btnAddNotes_Click(object sender, EventArgs e)
{
GrdNotes.ShowFooter = true;
BindNotes(int.Parse(hfID.Value));
}
protected void btnAddNotesSave_Click(object sender, EventArgs e)
{
TextBox txt = (TextBox)GrdNotes.FooterRow.FindControl("TxtNewNotes") ;
string sNotes = txt.Text;
}

"Can't find the value in the textbox" means that you can find the TextBox via FindControl but it's Text property returns String.Empty?
There is definitely text in the textbox, but it's returning "". if I
do a check txt.id it returns "TxtNewNotes" but txt.text = ""
Maybe you have forgotten to add a !IsPostBack check before you call BindNotes in Page_Load.
Thank you, yes I can't believe I forgot that!
Even the most experienced ASP.NET developers sometimes forget this ;)
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
BindNotes();
}

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.

ASP C# CheckBox within DetailsView

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

Get value of selected item in DataList

I'm trying to get the value from the selected item when I click a button.
Here is my code:
<asp:DataList ID="DataList1" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" Width="100%">
<ItemTemplate>
<p class="own"><asp:Image ID="Image1" runat="server" ImageUrl='<%# "GetImageDatafromDB.aspx?id=" + System.Convert.ToString(Eval("ID")) %>' Width="230" Height="250"/>
<br />
<span class="own1" style="width:230px;"><br /><asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>' Font-Bold="True" Font-Size="1.2em" ForeColor="White"/>
<br />
<asp:Label ID="Label5" runat="server" Text="Direktor :" style="color:#06D85F; float:left"></asp:Label><asp:Label ID="Label2" runat="server" CssClass="InFo" Text='<%# Eval("fattare") %>' Font-Italic="true"/>
<br />
<asp:Label ID="Label4" runat="server" Text="Year : " style="color:#06D85F; float:left;"></asp:Label><asp:Label ID="Label3" CssClass="InFo" runat="server" Text=' <%# (Eval("Ar")) %>' />
</br>
<asp:Button ID="Button1" runat="server" Text="Visa" CommandName="ButtonClick"/>
</span>
<asp:Label ID="Label6" runat="server" Visible="false" Text='<%# Eval("Name") %>'></asp:Label>
</p>
</ItemTemplate>
</asp:DataList>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string connectionString = ConfigurationManager.ConnectionStrings["Hemsida"].ConnectionString;
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(connectionString);
using (conn)
{
SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Movies", conn);
ad.Fill(dt);
}
DataList1.DataSource = dt;
DataList1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (DataListItem item in DataList1.Items)
{
Label myTempLabel = (Label)item.FindControl("Label6");
myTempLabel.Visible = true;
}
}
When I click the button, I get all of the names of all of the items, but I only want to get the name of the selected item.
On the ItemCommand event of DataList1, paste the following code:
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
DataList1.SelectedIndex = e.Item.ItemIndex;
myTempLabel.Text = "You selected: " + ((Label)DataList1.SelectedItem.FindControl("Label1")).Text;
myTempLabel.Visible = true;
}
I believe you need to use SelectedItem.
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.datalist.selecteditem(v=vs.110).aspx
Something like this:
protected void Button1_Click(object sender, EventArgs e)
{
if (DataList1.SelectedItem != null)
{
Label myTempLabel = (Label)DataList1.SelectedItem.FindControl("Label6");
myTempLabel.Visible = true;
}
}
Try changing this:
<asp:Button ID="Button1" runat="server" Text="Visa" CommandName="ButtonClick"/>
to This:
<asp:Button ID="Button1" runat="server" Text="Visa" OnClick="Button1_Click"
/>
Another alternative is to remove the code in the button and handle it on the Item_Command:
//Add item command to DataList
<asp:DataList ID="DataList1" runat="server" RepeatColumns="3" RepeatDirection="Horizontal" Width="100%" OnItemCommand="Item_Command">
void Item_Command(Object sender, DataListCommandEventArgs e)
{
// Set the SelectedIndex property to select an item in the DataList.
ItemsList.SelectedIndex = e.Item.ItemIndex;
//Get the selected Item
DataListItem selectedItem = DataList1.DataKeys[DataListList1.SelectedIndex];
//Get the label control
Label myTempLabel = (Label)selectedItem.FindControl("Label6");
myTempLabel.Visible = true;
// Not sure if this is needed.
//ItemsList.DataSource = CreateDataSource();
//ItemsList.DataBind();
}
If the textbox that gets the value is outside your update panel then try this:
if (e.CommandName == "selectitem")
{
DataList1.SelectedIndex = e.Item.ItemIndex;
TextBox2.Text = Label)DataList1.SelectedItem.FindControl("Label1")).Text;
}
If the textbox that gets the value is inside your update panel then try this
if (e.CommandName == "selectitem")
((Label)e.Item.FindControl("Label1")).Text = e.CommandArgument.ToString();

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