Find header value for a cell in a grid - c#

I have gridview, I want to do a foreach on it's rows and get the value from column's header where there's a Label for one cell from this row.
foreach (GridViewRow mainRow in grid1.Rows)
{
var header = mainRow.Cells[2].Parent.FindControl("LabelID");//is null
}
How do I find it ?

If you want the value in RowDataBound event then you can check RowType like this
if(e.Row.RowType == DataControlRowType.Header)
{
Label header = (Label)e.Row.FindControl("LabelID");
}

I would access the headerRow and enumerate through the according cells (on buttonClick or on RowDataBound ...)
default.aspx
<asp:GridView AutoGenerateColumns="false" ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:Label ID="headerLabel1" runat="server" Text="Headercolumn1"></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="itemLabel1" runat="server" Text='<%# Eval("name") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnGetHeader" runat="server" Text="GetHeader" OnClick="btnGetHeader_Click" />
default.aspx.cs
protected void btnGetHeader_Click(object sender, EventArgs e)
{
foreach (TableCell headerCell in GridView1.HeaderRow.Cells)
{
// or access Controls with index
// headerCell.Controls[INDEX]
Label lblHeader = headerCell.FindControl("headerLabel1") as Label;
if (lblHeader != null)
Debug.WriteLine("lblHeader: " + lblHeader.Text);
}
}

Related

How to work with DataBinder.Eval in GridView?

I have a GridView contains Lables, I need to show/hide Lables based on data.
Here is my GridView:
<asp:GridView ID="GridView_Profiles" runat="server" CssClass="grid" HorizontalAlign="Center"
OnRowDataBound="GridView_Profiles_OnRowDataBound" CellSpacing="1" GridLines="None"
AutoGenerateColumns="False" Width="90%">
<Columns>
<asp:Label ID="Label_SelectedCount" runat="server">
<span style="width:auto;color:White;background-color:#0c95be;height:auto;margin:0px;font-size:12px;cursor:pointer;padding-left:10px;padding-right:10px;padding-top:5px;padding-bottom:5px;">
<%#Eval("Count") %>
</span>
</asp:Label>
<asp:Label ID="lblNoCount" runat="server" Text="-"></asp:Label>
</Columns>
</asp:GridView>
In the above GridView RowDataBound how should I check for the bounding data using DataBinder.Eval?
Use this to get Label in RowDataBound event with DataBinder.Eval:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// find your label text in gridview with DataBinder.Eval
string count = DataBinder.Eval(e.Row.DataItem, "Count") as string;
// find your label control in gridview
Label lb = (Label)e.Row.FindControl("Label_SelectedCount");
// check condition to show/hide label (you use your own condition)
if(count > 0)
lb.Visible = true;
else
lb.Visible = false;
}
}
Or you can bind GridView with DataBinder.Eval like:
<asp:TemplateField HeaderText="Count"
<ItemTemplate>
<asp:Label ID="Label_SelectedCount" runat="server" >
<%# DataBinder.Eval(Container.DataItem, "Count")%>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
Note: You can also bind data to Label's Text attribute like this Text='<%#Eval("Count") %>'.

How to get the modified textbox value in c#?

I used a textbox in gridview to bind a value from db during pageload..
The problem is when i change the textbox value i could not get the modified value in c#, instead it gives the original value which had been there before i modified..
I am using nested GridViews...
kindly help me..
<asp:TemplateField HeaderText="Singles" >
<ItemTemplate>
<asp:HiddenField ID="hidqua" runat="server" Value='<%#bind("QualityName") %>' />
<asp:HiddenField ID="hidfau" runat="server" Value='<%#bind("FaultName") %>' />
<asp:TextBox ID="asptxtsingleg" runat="server" Text='<%# bind("singles") %>'></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
and below is my c# Coding
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "update")
{
foreach (GridViewRow row in grdInspection.Rows)
{
HiddenField hv = (HiddenField)row.FindControl("hidval");
GridView txtsi = (GridView)row.FindControl("grdInsiewChid");
foreach (GridViewRow row1 in txtsi.Rows)
{
HiddenField htn = (HiddenField)row1.FindControl("hdnPLength");
GridView nesgrid = (GridView)row1.FindControl("GridView1");
foreach (GridViewRow row2 in nesgrid.Rows)
{
HiddenField qn = (HiddenField)row2.FindControl("hidqua");
TextBox t = (TextBox)row2.FindControl("asptxtsingleg");
}
}
}
}
}
Assuming you are using button to fire the RowCommand event.
<asp:TemplateField HeaderText="Singles">
<ItemTemplate>
<asp:TextBox ID="asptxtsingleg" runat="server" Text='<%# Eval("singles") %>' Width="120px"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:Button ID="BtnEdit" runat="server" Text="Update" CommandName="updateData" CommandArgument='<%# Eval("Your_ID") %>' />
</ItemTemplate>
</asp:TemplateField>
Code behind:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "updateData")
{
//int i = Convert.ToInt32(e.CommandArgument);
GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
TextBox tb = (TextBox)row.FindControl("asptxtsingleg");
}
}
You can use below code to get the text box value in RowUpdating event
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
TextBox t= (TextBox)row.FindControl("asptxtsingleg");

Cannot get Values from Gridview

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

How can I select all data from GridView's current row

How can I select all data from GridViews current row..
I have a column for edit link in GridView. When "Edit" link button is clicked, I want to use that selected row's data. I am trying the following code, but it's returning me with an empty value
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = -1;
GridViewRow gvRow = gv.Rows[ e.NewEditIndex];
string selectedID = gvRow.Cells[3].Text;
}
<asp:GridView runat = "server" ID="gvRange0" SkinID="gridView" AutoGenerateColumns="False"
AllowSorting="True" OnRowCancelingEdit="gvRange_RowCancelingEdit" OnRowDeleting="gvRange_RowDeleting"
OnRowEditing="gvRange_RowEditing" OnRowUpdating="gvRange_RowUpdating"
Width="684px" OnRowDataBound="gvRange_RowDataBound"
DataMember="DefaultView" OnPageIndexChanged="gvRange_PageIndexChanged"
OnPageIndexChanging="gvRange_PageIndexChanging" OnSorting="gvRange_Sorting" DataKeyNames = "RANGE_ID"
OnSelectedIndexChanged="gvRange_SelectedIndexChanged" Height="65px" >
<Columns>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<ControlStyle Width="2px" />
<asp:LinkButton ID="lnkDelete0" runat="server" CssClass="lnk"
CausesValidation="False" CommandName="Delete"
Text="Delete" Visible="false"></asp:LinkButton>
<asp:CheckBox runat="server" ID="chkSelect" CssClass="lbl" Text="" AutoPostBack="False" OnCheckedChanged="chkSelect_CheckedChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<controlStyle width="2px" />
<asp:LinkButton ID="lnkEdit" runat="server" CssClass="lnk" CausesValidation="False" CommandName="Edit"
Text="Edit" ></asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="5px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Ranges" SortExpression="Sort_Ranges">
<ControlStyle Width="5px" />
<ItemTemplate>
<%#DataBinder.Eval(Container.DataItem,"Min_Age") %>
<%# CheckNull(DataBinder.Eval(Container.DataItem,"Max_Age")) %>
</ItemTemplate>
<%-- <ItemTemplate>--%>
<%--<asp:Label ID="lblStageName" CssClass="lbl" runat="server" Text='<%# Bind("Age_Range") %>' Width="1px"></asp:Label>--%>
<%-- </ItemTemplate>--%>
</asp:TemplateField>
<asp:TemplateField HeaderText="Range ID">
<ItemTemplate><%#DataBinder.Eval(Container.DataItem,"RANGE_ID") %></ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
There are 4 columns in the GridView. One contains check box, second is link button for edit, third databound with some value, fourth is the column which I want to use to get some values from database(that is primary key there) and this column is hidden.
sometime in gridview cell create child controls.
you can try this code. may be solve it.
protected void gv_RowEditing(object sender, GridViewEditEventArgs e)
{
gv.EditIndex = -1;
GridViewRow gvRow= (GridViewRow)(((Button)e.CommandSource).NamingContainer);
foreach (TableCell Tc in gvRow.Cells)
{
//if you are not getting value than find childcontrol of TabelCell.
string sss = c.Text;
foreach (Control ctl in Tc.Controls)
{
//Child controls
Label lb = ctl as Label;
string s = lb.Text;
sb.Append(s + ',');
}
}
}
I've noticed that you say you need to access the 4th column but you're using gvRow.Cells[3].Text;
The indexing in the Cell object is done from 1, so if you need to access the 4th row in the grid view try this:
string selectedID = gvRow.Cells[4].Text;
EDIT:
Could you please confirm two things for me
1)When you click on lnkEdit is the GridView1_RowEditing event being raised?
2)If yes, is the e.NewEditIndex value always showing up as '0'?
Attempt clicking the edit link on different rows, is the result always '0'?

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