Add ID to GridView Row - asp.net

How to add ID to GridView rows (IDs should be rendered)?
I am using .NET (C#). I have GridView control.
I have some javascript functions that are manipulating table rows, but it is necessary to have IDs for those rows:
<table>
<tr id=1> ...
<tr id=2> ... //id should come from database
..
My GridView is genereted from Data from DataBase. It is important not to have FAKE ROW IDS, but really row ids from DB (there are some ajax javascript function that updates DB based on those IDs and user manipulations with table).
Part of my GridView is the following:
<asp:GridView ID="grdNews" runat="server" BorderStyle="None" RowStyle-BorderStyle="None"
GridLines="None" CssClass="table" Style="white-space: nowrap" AutoGenerateColumns="False"
DataKeyNames="ID" AllowSorting="True" AllowPaging="true" OnSorting="grdNews_Sorting" OnRowDataBound="grdNews_RowDataBound">
<RowStyle BorderStyle="None" />
<HeaderStyle CssClass="nodrag" />
<Columns>
....
I have tried the following:
protected void grdNews_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.ID = grdNews.DataKeys[e.Row.RowIndex].Value.ToString();
}
}
This gives e.Row.ID the correct value, but this doesn't render this ID.
So, how to render IDs from DataBase for Rows in GridView?

Try following....
protected void grdNews_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
GridViewRow row = e.Row;
row.Attributes["id"] =grdNews.DataKeys[e.Row.RowIndex].Value.ToString();
}
}

The easiest way would be to use a hidden-field which you can access from client- and from server-side.
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:HiddenField ID="HiddenID" runat="server" Value='<%#Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
....
</Columns>

Vb.net code
Private Sub gvPayments_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvPayments.RowDataBound
Dim counter As Integer = 0
For Each oItem As GridViewRow In gvPayments.Rows
counter += 1
oItem.Cells(1).Text = counter.ToString()
oItem.Attributes("id") = "tr_" + counter.ToString
Next
End Sub

Make sure that:
You are calling your database Binding function out side the IsPOstback event.
You have not mentioned your RowDatabound Event Signature in Grid Definition

Related

GridView Row FindControl(x) Text is blank

I have a GridView where I want to hide some of the rows when the price is 0. When I try to check the value I get a blank string for all rows.
Markup: non relevant rows have been removed for readability. getProductInfo and getPrice are lookup functions receiving and returning strings
<asp:GridView ID="gvRebuild" runat="server" AutoGenerateColumns="false" Width="100%" OnRowDataBound="gvRebuild_RowDataBound">
<Columns>
<asp:BoundField ... />
<asp:TemplateField ... />
</asp:TemplateField>
<asp:TemplateField HeaderText="Price" ItemStyle-Width="12%">
<ItemTemplate>
<asp:Label runat="server" ID="price" ><%# getPrice(getProductInfo(Eval("fieldName")))%></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ... />
</Columns>
</asp:GridView>
Code Behind:
Protected Sub gvRebuild_RowDataBound(sender As Object, e As GridViewRowEventArgs)
Dim p As Label = e.Row.FindControl("price")
If p IsNot Nothing Then
Debug.Print(String.Format("*{0}*", p.Text))
If p.Text = "$0.00" Then
e.Row.Visible = False
End If
End If
End Sub
The debug statement is confirming that all values found in the "price" control are blank. I have also confirmed via debugger that the getPrice function is returning the correct value and firing before the RowDataBound event handler for each row.
You have to check the RowType. The first row will be the header row. The header row does not contain the TextBox, hence the NULL error.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
//use findcontrol here
}
}
VB
Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
If (e.Row.RowType = DataControlRowType.DataRow) Then
'use findcontrol here
End If
End Sub
Update
I see what you mean now. It is the value that is NULL not the control itself.
I did some testing and it turns out that if you use your method it does not work. But change it to this and it will.
<asp:Label runat="server" ID="price" Text='<%# getPrice(getProductInfo(Eval("fieldName"))) %>'></asp:Label>
It seems that the binding of data inside the tag is done after the row or gridview has completed, but the Text property is set right away.

Get clicked cell in gridview asp.net

I got gridview that I fill with data from my database. I would like to catch an event of click and to get attributes of the cell row and column.
all I found is row click that I can get the row clicked.
also, if there is other component to deploy the data and can get me the cell click event is good enough for me.
HTML:
<div class="grid">
<asp:GridView ID="HistoricGrid" runat="server"></asp:GridView>
</div>
C#
DBconnection db = new DBconnection();
string strtable = "select * from StudentVisit";
DataTable dt = db.ReadDataTable(strtable);
HistoricGrid.DataSource = dt; HistoricGrid.DataBind();
thanks for the help,
Moshe
You should try this.
<asp:GridView ID="GridView1" AutoGenerateColumns="False" ShowHeader="True" runat="server" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:BoundField HeaderText="Value" DataField="ItemValue" ReadOnly="true" />
<asp:BoundField HeaderText="Text" DataField="ItemText" ReadOnly="true" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
aspx.cs file
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if ( e.Row.RowType == DataControlRowType.DataRow )
{
LinkButton linkButton = (LinkButton)e.Row.FindControl("LinkButton1");
if (linkButton != null)
{
linkButton.Attributes.Add("onclick", "window.open('someURL'); return false;");
}
}
}
You can use below code
private void gv_Cell_Click(object sender, GridViewCellEventArgs e)
{
int cellindex=e.CellIndex;
int rowindex =e.rowindex;
var value = gv.Rows[rowindex].Cells[cellindex].value;
}

AspxGridView checkbox checked column value

I am using one aspxGridview where I used checkbox. Now I need when I check any of the row particular column value I should get in server side to complete my business logic.
Below is the gridview used:
<dx:ASPxGridView KeyFieldName="PracticeID" ID="ASPxGrd" runat="server" ClientInstanceName="grid"
ClientIDMode="AutoID" AutoGenerateColumns="false" Width="100%" OnSelectionChanged="ASPxGrd_SelectionChanged">
<Columns>
<dx:GridViewDataColumn VisibleIndex="0" Name="CheckBoxColumn">
<DataItemTemplate>
<dx:ASPxCheckBox ID="ASPxCheckBox1" runat="server" OnCheckedChanged="ASPxCheckBox1_CheckedChanged" AutoPostBack="true">
</dx:ASPxCheckBox>
</DataItemTemplate>
</dx:GridViewDataColumn>
<dx:GridViewDataColumn FieldName="PracticeName" Caption="Description" VisibleIndex="1">
<FooterTemplate>
Total:
</FooterTemplate>
</dx:GridViewDataColumn>
</dx:ASPxGridView>
I have tried to use oncheckedevent in checkbox with auto postback true and used code to get selected row like below:
protected void ASPxCheckBox1_CheckedChanged(object sender, EventArgs e)
{
ASPxGridView grid = sender as ASPxGridView;
string currentMasterKey = Convert.ToString(grid.GetMasterRowKeyValue());
}
but getting null value of grid object.
Need help.
In your example you have used DataItemTemplate, so in that case the sender will be the control which is added in that data template i.e ASPxCheckBox and you are casting it to grid bcoz of that it is getting null.
try out below snippet.
protected void ASPxCheckBox1_CheckedChanged(object sender, EventArgs e)
{
ASPxCheckBox checkBox = sender as ASPxCheckBox;
var grid = (checkBox.NamingContainer as DevExpress.Web.ASPxGridView.GridViewDataItemTemplateContainer).Grid;
string currentMasterKey = Convert.ToString(grid.GetMasterRowKeyValue());
}
I found this answer before and it's working fine like below:
for (int i = 0; i < ASPxGrd.VisibleRowCount; i++)
{
ASPxCheckBox chk = ASPxGrd.FindRowCellTemplateControl(i, null, "ASPxCheckBox1") as ASPxCheckBox;
if (chk.Checked)
{
if (i == 0)
{
practiceName = ASPxGrd.GetRowValues(i, "PracticeName").ToString();
}
}
}
using this code i am able to get selected checkbox column value.

itemTemplate item id not existing in code behind

I am trying to create textboxes that are equal to the number of rows in grid view (databound from db). here is my markup
<asp:GridView ID="quizGrid" runat="server" CssClass="Grid" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="admissionNO" HeaderText="Admission NO"/>
<asp:BoundField DataField="studentName" HeaderText="Name" />
<asp:TemplateField>
<ItemTemplate>
<asp:Textbox runat="server" ID="marks" > </asp:Textbox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
but when i use the marks in code behind it says
quizGrid_marks_0 does not exists in the current context
what im doing wrong here?
You can't access your textbox like that in code behind file, rather you need to find them in RowDataBound event like this:-
protected void quizGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
TextBox marks = (TextBox)e.Row.FindControl("marks");
txtMarks.Text = "Test";
}
}
Edit:
Okay, suppose you have a button btnGetData with button click event as btnGetData_Click, then you can find the textbox text by looping through the gridview rows like this:-
protected void btnGetData_Click(object sender, EventArgs e)
{
GridView quizGrid = (GridView)Page.FindControl("quizGrid");
foreach (GridViewRow row in quizGrid.Rows)
{
TextBox marks = (TextBox)row.FindControl("marks");
}
}

Checkbox on GridView always returning False

I have a GridView with a Checkbox on the first column:
<asp:GridView ID="dgNumeradores" runat="server" AutoGenerateColumns="False" CellPadding="4" DataKeyNames="ItemID">
<Columns>
<asp:TemplateField HeaderText="Seleccionar">
<ItemTemplate>
<asp:CheckBox runat="server" ID="chkChecked" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Item" DataField="Description">
</asp:BoundField>
<asp:BoundField HeaderText="Plantilla" DataField="Template">
</asp:BoundField>
</Columns>
</asp:GridView>
Now in the code behind I try to update the Checked column on the DataTable acting as datasource for the GridView (since, as you can see above, the Checkbox column is not bound to the datasource for reasons you probably know.):
Protected Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
For Each dr As GridViewRow In Me.dgNumeradores.Rows
Me.itemsNumTable.Select("ItemID = '" & dgNumeradores.DataKeys(dr.RowIndex).Value & "'")(0)("Checked") = DirectCast(dr.Cells(0).FindControl("chkChecked"), CheckBox).Checked
Next
'Some more unimportant-for-this-question code
Catch ex As Exception
tableInfo.ShowError(ex.Message)
End Try
End Sub
The thing is that the Checkbox.Checked always returns False.
How can I get the checked state of the Checkboxes in this scenario? Or what would be the best approach into updating the aforementioned column?
P.S. Note that click on the checkboxes doesn't post back. Nothing happens on the page until the user clicks Save (and that is the intended behavior).
Are you binding the GridView in Page Load? If that is the case use IsPostBack
IF Not IsPostBack Then
DataBind()
End IF
Should you not have the AutoPostback property set to true?
<asp:CheckBox runat="server" ID="chkChecked" AutoPostback="true" />
I have two columns in my GridView. The first column contains filenames,
the second column contains Checkboxes. Once the user has selected an arbitrary
number of Checkboxes then by clicking a button the selected files can be
downloaded.
My markup is as follows
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="Available Schemas"
DataField="SchemaFileName"
SortExpression="UserId">
</asp:BoundField>
<asp:TemplateField HeaderText="Select Schema">
<ItemTemplate>
<asp:CheckBox runat="server" ID="SelectedFiles" checked= '<%# Eval("checkValue") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My CodeBehind part is as follows
protected void Page_Load(object sender, EventArgs e)
{
GenerateDownloadLinks();
if (!IsPostBack)
{
GridView1.DataSource = listOfData;
GridView1.DataBind();
}
}
listOfData is populated in GenerateDownloadLinks() and then it is bind to GridView1.
Once the user selected files and clicks download then my code loops through
the rows of the GridView and when the CheckBox is checked it updates the initially
false value of the data entry to make sure which files should be made available for
download.
protected void GetFiles_Click(object sender, EventArgs e)
{
int i = 0;
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkRow = (row.Cells[1].FindControl("SelectedFiles") as CheckBox);
if (chkRow.Checked)
{
listOfData[i].CheckValue = true;
}
i++;
}
}
Gridview fills perfectly even when it is not binded in Page.IsPostBack block, but here checkbox will always return false.
Bind gridview in Page.IsPostBack, and it would run perfectly fine.
Use below code
IF Not IsPostBack Then
DataBind()
End IF
And then Checkbox.Checked will return true.

Resources