I have a databound gridview and I have a TextBox template field inside that
The markup look like the below
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="tbl_costing" runat="server" AutoGenerateColumns="False" OnRowDataBound="tbl_costing_RowDataBound" CellPadding="4" ForeColor="#333333" GridLines="None" Width="1023px" ShowHeaderWhenEmpty="True">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Consumption" SortExpression="Consumption">
<ItemTemplate>
<asp:UpdatePanel ID="UpdatePanel3" runat="server">
<ContentTemplate>
<asp:TextBox ID="txt_consumption" runat="server" Text='<%# Bind("Consumption") %>' AutoPostBack="True" OnTextChanged="txt_consumption_TextChanged"></asp:TextBox>
</ContentTemplate>
</asp:UpdatePanel>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ControlToValidate="txt_consumption" ErrorMessage="Required" ForeColor="#CC3300">*
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ControlToValidate="txt_consumption" ErrorMessage="Enter valid Consumption" ForeColor="Red" ValidationExpression="^[\d.]+$">*
</asp:RegularExpressionValidator>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Now I need to get the row index of the Textbox on post back event I did it like this
protected void txt_consumption_TextChanged(object sender, EventArgs e)
{
try
{
TextBox txtcons = (TextBox)sender;
GridViewRow currentRow = (GridViewRow)txtcons.Parent.Parent; // Error Here .....
int rowindex = 0;
rowindex = currentRow.RowIndex;
calculateperdozen(currentRow);
}
catch (Exception)
{
}
}
Can anyone suggest be a way to get the currentRow or rowindex?
Sorry that I had not updated the solution I got for this problem till now. Let it help somebody who have the same query
I created a class which will loop trough till it reaches the Gridviewrow as naming container
public static class ControlTreeExtensions
{
public static TContainer ClosestContainer<TContainer>(this Control theControl) where TContainer : Control
{
if (theControl == null) throw new ArgumentNullException("theControl");
Control current = theControl.NamingContainer;
TContainer result = current as TContainer;
while (current != null && result == null)
{
current = current.NamingContainer;
result = current as TContainer;
}
return result;
}
}
Then in my Click event or Change even I called the function
protected void txt_consumption_TextChanged(object sender, EventArgs e)
{
try
{
TextBox txtcons = (TextBox )sender;
GridViewRow currentRow = txtcons.ClosestContainer<GridViewRow>();
int rowindex = 0;
rowindex = currentRow.RowIndex;
calculateperdozen(currentRow);
}
catch (Exception)
{
}
}
Related
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
}
}
Hello i have a gridview Naming FolderGridView. in the GridView There is a template field and inside the template field i am specifying a Linkbutton. Now i cannot get values from the linkButton in my codeBehind.
<asp:GridView ID="FolderGridView" runat="server"
AutoGenerateColumns = "False"
AllowPaging ="True" OnPageIndexChanging ="FolderGridView_PageIndexChanging" CellPadding="4" ForeColor="#333333" GridLines="None"
>
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="FolderCheckBox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Folder Name">
<ItemTemplate>
<asp:LinkButton Text='<%#Eval("File Name")%>' PostBackUrl='<%# String.Format("InsideFolder.aspx?FolderName={0}", Eval("File Name") ) %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
my code Behind
for (int i = 0; i < FolderGridView.Rows.Count; i++)
{
CheckBox chk = (CheckBox)FolderGridView.Rows[i].FindControl("FolderCheckBox");
if (chk.Checked == true)
{
string FileName = (string)FolderGridView.Rows[i].Cells[1].Text.ToString();
}
}
I have debugged the code behind portion. In FileName i get an empty string when i get to this point. How to get values from the template field then?
The text in the cell is inside the LinkButton control, so first you have to get the LinkButton control of the GridView row, and then you can access the Text property. The following code should work in your case:
for (int i = 0; i < FolderGridView.Rows.Count; i++){
CheckBox chk = (CheckBox)FolderGridView.Rows[i].FindControl("FolderCheckBox");
if (chk.Checked == true){
foreach (Control ctl in FolderGridView.Rows(i).Cells(1).Controls) {
if (ctl is LinkButton) {
string filename = ((LinkButton)ctl).Text;
}
}
}
replace Link Button with
EDIT:
For LinkButton:
<asp:LinkButton ID="LinkButton1" AutoPostBack="True" OnClick="someMethod" Text='<%#Eval("File Name")%>' PostBackUrl='<%# String.Format("InsideFolder.aspx?FolderName={0}", Eval("File Name") ) %>' runat="server" />
and code Behind
protected void someMethod(object sender, EventArgs e)
{
foreach (GridViewRow item in GridView5.Rows)
{
CheckBox chk = (CheckBox)item.FindControl("FolderCheckBox");
if (chk.Checked == true)
{
string probname = chk.Text;
}
}
}
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();
}
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;
}
}
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";
}
}