Cannot get Values from Gridview - c#

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

Related

Template TextBox feild inside UpdatePanel in Asp.net WebForm

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

how to add different control in gridview row

I have a gridview which I populate from the list data. every row in the gridview has a text box. there is one row within the gridview which I want a dropdown control rather then the textbox. I can't figure out how to change the textbox to dropdown control from a row in the grid.
My gridview below:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" style="width:100%;" ShowHeader="false"
CellPadding="3" BackColor="White" ForeColor="Black" Font-Bold="false" GridLines="None"
RowStyle-CssClass="GridRow">
<Columns>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lbl_ItemID" runat="server" Text='<%# Eval("GroupItemTypeID") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="false">
<ItemTemplate>
<asp:Label ID="lbl_ItemCode" runat="server" Text='<%# Eval("GroupItemTypeCode") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="310px" >
<ItemTemplate>
<asp:Label ID="lbl_ItemValuesName" runat="server" Text='<%# Eval("ControlName") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="245px">
<ItemTemplate>
<asp:TextBox ID="txtPrice" runat="server" CssClass="form-control"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-CssClass="RowWid">
<ItemTemplate>
<asp:Label ID="lbl_IsPercentbased" runat="server" Text='<%# Eval("PercentBasedText") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="70px">
<ItemTemplate>
<asp:CheckBox ID="ChkIsPercent" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
private void GetItemValues()
{
List<Entities.ItemValues> IValues = new List<Entities.ItemValues>();
IValues = BLL.PriceGroupItemValues.GetAllPriceGroupItemValues();
GridView1.DataSource = IValues;
GridView1.DataBind();
}
You can go for this approach in your case :
Put a TextBox and DropDown both in that TemplateField where your TextBox is currently, and set Visible=false in your Dropdown.
Now in your code-behind, you can use the GridView.RowDataBound event to alternatively display the TextBox or the Dropdown whenever and wherever you require. Something like this :
public void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
// set Dropdown visible = true/false as per your requirement.
}
else
{
// set Textboxvisible = true/false as per your requirement.
}
}
This event will fire up for ear row in your GridView and based on the condition that is specified, you can manipulate which control you want to show in that particular row. You can find the dropdown control like this :
foreach (GridViewRow row in GridView1.Rows)
{
categoryName = ((DropDownList)row.FindControl("ddlCategoryName"));
}
Hope this helps.
Use a placeholder control instead of a textbox and programmatically add either a textbox or DDL to the Placeholder control in the rowdatabound event based on your criteria
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="SqlDataSource1"
DataKeyNames="user_id">
<Columns>
<asp:BoundField DataField="user_id" HeaderText="user_id" ReadOnly="True" InsertVisible="False"
SortExpression="user_id"></asp:BoundField>
<asp:BoundField DataField="user_logon" HeaderText="user_logon" SortExpression="user_logon">
</asp:BoundField>
<asp:TemplateField>
<ItemTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Sample DataSources
'Primary Datasource to bind to the gridview
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString='<%$ ConnectionStrings:SomeConnectionString %>'
SelectCommand="select top 10 user_id, user_logon from your_user_table"></asp:SqlDataSource>
'Secondary datasource to bind to the ddl
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString='<%$ ConnectionStrings:SomeConnectionString %>'
SelectCommand="select top 5 user_id, user_logon from your_user_table"></asp:SqlDataSource>
Code behind, based on the whether the user_id is odd or even I place one or the other control:
Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ph As PlaceHolder = e.Row.FindControl("PlaceHolder1")
If GridView1.DataKeys(e.Row.RowIndex).Value Mod 2 = 0 Then
Dim tb As New TextBox()
tb.Enabled = False
tb.Text = CType(e.Row.DataItem, DataRowView)("user_logon")
ph.Controls.Add(tb)
Else
Dim ddl As New DropDownList()
ddl.DataSourceID = SqlDataSource2.ID
ddl.DataTextField = "user_logon"
ddl.DataValueField = "user_id"
ph.Controls.Add(ddl)
ddl.DataBind()
End If
End If
End Sub
EDIT based on your Comments:
Private Sub GridView1_RowDataBound(sender As Object, e As GridViewRowEventArgs) Handles GridView1.RowDataBound
If e.Row.RowType = DataControlRowType.DataRow Then
Dim ph As PlaceHolder = e.Row.FindControl("PlaceHolder1")
If CType(e.Row.DataItem, DataRowView)("GroupItemTypeID") ="SUBFREQ" Then
Dim ddl As New DropDownList()
ddl.DataSourceID = <substitute your requirements>
ddl.DataTextField = ...
ddl.DataValueField = ...
ph.Controls.Add(ddl)
ddl.DataBind()
Else
Dim tb As New TextBox()
tb.Enabled = ...whatever...
tb.Text = CType(e.Row.DataItem, DataRowView)("GroupItemTypeID")
ph.Controls.Add(tb)
End If
End If
End Sub
Did some work around with the solution Harvey provided and my existing code. Posting my answer here.
In the gridview, created 2 control and visibility of one control(dropdown) to false
<asp:TemplateField ItemStyle-Width="245px">
<ItemTemplate>
<asp:TextBox ID="txtPrice" runat="server" CssClass="form-control"></asp:TextBox>
<asp:DropDownList ID="ddFrequencyBilling" runat="server" CssClass="form-control" Visible="false"></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
In the RowDataBound event of the gridview
if (e.Row.RowType == DataControlRowType.DataRow)
{
//foreach( GridViewRow row in GridView1.Rows)
//{
String ItemCode = (e.Row.FindControl("lbl_ItemCode") as Label).Text;
if ( ItemCode == "SUBFREQ")
{
List<Entities.ItemValues> PGItemValues = new List<Entities.ItemValues>();
TextBox TextBoxtemp = ((TextBox)e.Row.FindControl("txtPrice"));
TextBoxtemp.Visible = false;
Label lbel = ((Label)e.Row.FindControl("lbl_IsPercentbased"));
lbel.Visible = false;
CheckBox chk = ((CheckBox)e.Row.FindControl("ChkIsPercent"));
chk.Visible = false;
DropDownList dd1 = ((DropDownList)e.Row.FindControl("ddFrequencyBilling"));
dd1.Visible = true;
PGItemValues = BLL.PriceGroupItemValues.GetItemValueOnCode(ItemCode, 1);
dd1.DataSource = PGItemValues;
dd1.DataTextField = "IValue";
dd1.DataValueField = "ItemCode";
dd1.DataBind();
}
//}
}
and yes it worked. Thanks alot guys.

How to validate Textbox when Checkbox is checked in RadGrid using JavaScript

How do you validate a textbox when a checkbox is checked in a RadGrid using JavaScript?
I tried to use the CheckBox_CheckedChanged event but it is not working. Please tell me how to validate if the textbox is empty or not when a checkbox is checked in a RadGrid in ASP.NET.
C#:
protected void CheckBox1_CheckedChanged1(object sender, EventArgs e)
{
foreach (GridDataItem item in radGridSahreaJob.MasterTableView.Items)
{
TextBox txtMaxResumes = (TextBox)item.FindControl("txtMaxResumes");
CheckBox chkBox = (CheckBox)item.FindControl("chkIsCandidateSelected");
string str = txtMaxResumes.Text;
if (chkBox.Checked && string.IsNullOrEmpty(str))
{
ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "alert", "getMessagetest('ShareaJob');", true);
}
}
}
ASP.NET:
<Columns>
<telerik:GridTemplateColumn UniqueName="chkSelect" lowFiltering="false">
<HeaderTemplate>
<asp:CheckBox ID="chkSelectAll" runat="server" OnClick="return SelectAllCandidates(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkIsCandidateSelected" runat="server" OnClick="return CandidateRowChecked();" AutoPostBack="True" oncheckedchanged="CheckBox1_CheckedChanged1"/>
</ItemTemplate>
</telerik:GridTemplateColumn>
<telerik:GridTemplateColumn HeaderText="Max.Resume(s) can upload" HeaderStyle-HorizontalAlign="Center" ShowFilterIcon="false" AllowFiltering="false">
<ItemTemplate>
<asp:TextBox ID="txtMaxResumes" runat="server" CssClass="rgf_txt_area_l2" Text="3" Width="80px" MaxLength="2">
</asp:TextBox>
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
JavaScript:
function getMessagetest(entity) {
if (entity == 'ShareaJob') {
radalert("Please enter number !", 370, 150, "Alert");
}
}
finally i got solution. Thanks.
foreach (GridDataItem item in radGridSahreaJob.MasterTableView.Items)
{
CheckBox CheckBox1 = item.FindControl("chkIsCandidateSelected") as CheckBox;
TextBox TextBox1 = item.FindControl("txtMaxResumes") as TextBox;
string strTxtResumes = TextBox1.Text;
if (CheckBox1 != null && CheckBox1.Checked && string.IsNullOrEmpty(strTxtResumes))
{
hdnCheckBox.Value = "1";
}
}

Find header value for a cell in a grid

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

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