Paging in child grid view not working - asp.net

Hi all I am doing a program with a nested gridview my design is as follows
<asp:Panel CssClass="grid" ID="pnlCust" runat="server">
<asp:UpdatePanel ID="pnlUpdate" runat="server">
<ContentTemplate>
<asp:GridView AllowPaging="True" ID="gvCustomers" AutoGenerateColumns="False" DataKeyNames="EmpID"
runat="server" ShowHeader="true" BackColor="White" BorderColor="#DEDFDE" BorderStyle="None"
BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Vertical" >
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Panel CssClass="group" ID="pnlCustomer" runat="server">
<%--<asp:Image ID="imgCollapsible" CssClass="first" ImageUrl="~/Assets/img/plus.png"
Style="margin-right: 5px;" runat="server" /><span class="header">
<%#Eval("EmpID")%>
:
<%#Eval("empname")%>--%>
<asp:RadioButton ID="rdbtn" runat="server" onclick="RadioCheck(this);" OnCheckedChanged="radio_changed" Text='<%# Bind("EmpID") %>'
AutoPostBack="true"></asp:RadioButton>
</asp:Panel>
<asp:Panel Style="margin-left: 20px; margin-right: 20px" ID="pnlOrders" runat="server">
<asp:GridView AutoGenerateColumns="false" CssClass="grid" ID="gvOrders" runat="server"
PageSize="1" ShowHeader="true" EnableViewState="false" DataKeyNames="EmpID" AllowPaging="true"
OnPageIndexChanging="gvOrders_PageIndexChanging">
<RowStyle CssClass="row" />
<AlternatingRowStyle CssClass="altrow" />
<Columns>
<asp:BoundField HeaderText="Employee Id" DataField="EmpID">
<ItemStyle HorizontalAlign="Center" Width="100px" />
</asp:BoundField>
<asp:TemplateField ItemStyle-CssClass="rownum">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderStyle-BackColor="#EFF1F1" ItemStyle-HorizontalAlign="Center"
ItemStyle-Height="25" HeaderStyle-Width="50" ItemStyle-Width="50">
<HeaderTemplate>
<input id="chkBoxAll" type="checkbox" onclick="checkAllBoxes()" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkBoxChild" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PayPeriodNumber" HeaderText="PayPeriod" HeaderStyle-BackColor="#EFF1F1"
ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="80" ItemStyle-Width="80">
</asp:BoundField>
<asp:BoundField DataField="PayRollYear" HeaderText="Payroll Year" HeaderStyle-BackColor="#EFF1F1"
ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="100" ItemStyle-Width="100">
</asp:BoundField>
<asp:BoundField DataField="PaymentDate" HeaderText="Payment Date" HeaderStyle-BackColor="#EFF1F1"
ItemStyle-HorizontalAlign="Center" HeaderStyle-Width="110" ItemStyle-Width="110">
</asp:BoundField>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>
Image of that on Page load
On selecting one of the radio buttons I will show the corresponding Employee details which is as follows
I have written paging for gridview as follows
if (!Page.IsPostBack)
{
GridViewChildPageIndex();
}
private void GridViewChildPageIndex()
{
DataTable dtPageIndex = new DataTable();
dtPageIndex.Columns.Add("PageIndex", typeof(int));
for (int i = 0; i < gvCustomers.Rows.Count; i++)
{
dtPageIndex.Rows.Add("0");
}
Session["ChildPageIndex"] = dtPageIndex;
}
Paging code of child gridview is as follows
protected void gvOrders_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView gvwChild = (GridView)sender;
//GridViewRow gvRowParent = ((System.Web.UI.WebControls.GridView)sender).Parent as GridViewRow;
GridViewRow gvRowParent = gvwChild.Parent as GridViewRow;
gvwChild.PageIndex = e.NewPageIndex;
if (Session["ChildPageIndex"] != null)
{
DataTable dtPageIndex = (DataTable)Session["ChildPageIndex"];
dtPageIndex.Rows[gvRowParent.RowIndex][1] = e.NewPageIndex; // *I am getting error here as Object reference not set to an Object can any one tell where I went wrong*
}
BindChildGrdView(gvCustomers.DataKeys[gvRowParent.RowIndex].Value.ToString(), gvwChild);
}
Stack Trace
at _Default.gvOrders_PageIndexChanging(Object sender, GridViewPageEventArgs e) in d:\Projects\GridView-Collapsible\GridView-Collapsible\Default.aspx.cs:line 54
at System.Web.UI.WebControls.GridView.OnPageIndexChanging(GridViewPageEventArgs e)
at System.Web.UI.WebControls.GridView.HandlePage(Int32 newPage)
at System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup)
at System.Web.UI.WebControls.GridView.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.GridView.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

This may help you out:
In the gvOrders_PageIndexChanging function, use
GridViewRow gvRowParent = gvwChild.Parent.Parent as GridViewRow;
And inside the if condition
if (Session["ChildPageIndex"] != null)
{
DataTable dtPageIndex = (DataTable)Session["ChildPageIndex"];
dtPageIndex.Rows[gvRowParent.RowIndex][0] = e.NewPageIndex; // *I am getting error here as Object reference not set to an Object can any one tell where I went wrong*
}
And also could you debug and check if gvRowParent is an instantiated object in the second line of this function.

Related

Page with GridView ASP.NET not display in browser

I try to bind data from code behind into a GridView. I don't know what's wrong cause there is no error from debug, but when I try to display the page in browser it doesn't display (the hole page won't come up).
<asp:GridView runat="server" ID="productCart" AutoGenerateColumns="false" EmptyDataText="There is nothing in your shopping cart." GridLines="None" Width="100%" CellPadding="5" ShowFooter="true" DataKeyNames="ProductId">
<HeaderStyle HorizontalAlign="Left" BackColor="#F36EA7" ForeColor="#FFFFFF" />
<FooterStyle HorizontalAlign="Right" BackColor="#6C6B66" ForeColor="#FFFFFF" />
<AlternatingRowStyle BackColor="#F8F8F8" />
<Columns>
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtQuantity" Columns="5" Text='<%# Eval("Quantity") %>'></asp:TextBox><br />
<asp:LinkButton runat="server" ID="btnRemove" Text="Remove" CommandName="Remove" CommandArgument='<%# Eval("ProductId") %>' style="font-size:12px;"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="UnitPrice" HeaderText="Price" ItemStyle-HorizontalAlign="Right" HeaderStyle-HorizontalAlign="Right" DataFormatString="{0:C}" />
<asp:BoundField DataField="TotalPrice" HeaderText="Total" ItemStyle-HorizontalAlign="Right" HeaderStyle-HorizontalAlign="Right" DataFormatString="{0:C}" />
</Columns>
</asp:GridView>
.cs:
public partial class Cart : System.Web.UI.Page
{
UserSingleton activeUser = UserSingleton.Instance;
List<CartItem_Test> CartItems = null;
protected void Page_Load(object sender, EventArgs e)
{
DataTable dataTable = Access.GetInfo("CartPerUserID", "*", "UserID=" + activeUser.get_user().ID);
if (dataTable.Rows.Count > 0)
{
CartItems = new List<CartItem_Test>(dataTable.Rows.Count);
foreach (DataRow row in dataTable.Rows)
{
CartItem_Test cartItem = new CartItem_Test(row);
CartItems.Add(cartItem);
}
}
if (!IsPostBack)
{
productCart.DataSource = CartItems;
productCart.DataBind();
}
}

one dataGrid with 3 search option

My scenario is : I have one dataGrid with 5-6 columns. i have 3 filters which use 3 SQL queries methods in codeBehind :SearchByName(), SearchByValue() , SearchByDate().I have fourth method show DefaultShow() which display all data without any filters.
Basicly I want when Page is loaded DefaultShow() method to load and then user can choose option for search with RadioButtonList
DefaultShow() code is :
public void DefaultShow()
{
string connectionString = cs.getConnection();
string query = "select Id ,name,value,Description,DateCreate from AllCostView where IdUser = '" + cui.getCurrentId() + "'";
using (SqlConnection myConnection = new SqlConnection(connectionString))
{
myConnection.Open();
SqlCommand command = new SqlCommand(query, myConnection);
SqlDataAdapter mySqlAdapter = new SqlDataAdapter(command);
using (DataTable myDataTable = new DataTable())
{
mySqlAdapter.Fill(myDataTable);
GridViewCost.DataSource = myDataTable;
GridViewCost.DataBind();
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
DefaultShow();
}
But this not work what am I miss?
My gridViewCode is this :
<div class ="gridView">
<asp:GridView ID="GridViewCost" runat="server" AutoGenerateColumns="False" CaptionAlign="Top"
ShowFooter="True" ShowHeaderWhenEmpty="True" Font-Overline="False"
Font-Strikeout="False" Font-Underline="False"
AllowPaging="true"
PageSize="5"
CssClass="mGrid"
PagerStyle-CssClass="pgr"
AlternatingRowStyle-CssClass="alt" OnPageIndexChanging="GridViewCost_PageIndexChanging" OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged" >
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
<Columns>
<asp:BoundField DataField="Id" HeaderText="Номер" />
<asp:TemplateField HeaderText="Име">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
<ControlStyle Width="100px" />
</asp:TemplateField>
<asp:BoundField DataField="Value" HeaderText="Стойност" />
<asp:BoundField DataField="Description" HeaderText="Описание" />
<asp:BoundField DataField="DateCreate" HeaderText="Дата" />
</Columns>
<AlternatingRowStyle />
<HeaderStyle HorizontalAlign="Right"/>
<PagerStyle />
<RowStyle BorderColor="Black" BorderStyle="Solid" BorderWidth="1px" HorizontalAlign="Center" />
</asp:GridView>
If it's needed i will post more code . Thanks.

Paging GridView Issues

I just read some articles about paging gridview but I couldn't make it...
There is my full gridview's code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" style="font-family: Verdana, Arial, Sans-Serif;"
CssClass="gridview" OnSorting="GridView_Sorting"
DataKeyNames="id"
AllowSorting ="True" BackColor="#CCCCCC"
BorderStyle="Inset" BorderWidth="2px" BorderColor="GrayText"
CellPadding="1"
CellSpacing="5"
HeaderStyle-HorizontalAlign="Center"
OnRowDataBound="GridView1_RowDataBound"
ForeColor = "Black" RowStyle-CssClass="gridview"
OnRowCommand="GridView1_RowCommand" AllowPaging="True"
OnPageIndexChanging="GridView1_PageIndexChanging" PageSize="5">
<AlternatingRowStyle BackColor="#CCCCCC" />
<columns>
<asp:BoundField HeaderText="ID" DataField="id" />
<asp:BoundField HeaderText="PRIORIDADE" DataField="prioridade"
ItemStyle-HorizontalAlign="Center">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="SITUAÇÃO" DataField="situacao" ItemStyle-HorizontalAlign="Center" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="RESPONSAVEL" DataField="responsavel" HeaderStyle-Width="65px" ItemStyle-HorizontalAlign="Center">
<HeaderStyle Width="65px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="DATA DE CADASTRO" DataField="dt_cadastro" DataFormatString="{0:dd/MM/yyyy}" HeaderStyle-Width="60px" SortExpression="dt_cadastro"
ItemStyle-HorizontalAlign="Center" >
<HeaderStyle Width="60px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="PREVISÃO DE TÉRMINO" DataField="previsao_termino" DataFormatString="{0:dd/MM/yyyy}" HeaderStyle-Width="60px"
ItemStyle-HorizontalAlign="Center">
<HeaderStyle Width="60px" />
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="PROJETO" DataField="projeto" ItemStyle-HorizontalAlign="Center">
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="FUNCIONALIDADE" DataField="funcionalidade"
ItemStyle-HorizontalAlign="Center" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField HeaderText="CLUBE" DataField="clube"
ItemStyle-HorizontalAlign="Center" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField HeaderStyle-Width="70px" HeaderText="VISUALIZAR" >
<ItemTemplate>
<asp:Button ID="Btn_Visualizar" runat="server" Text="VISUALIZAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana, Arial" OnClick="Btn_Visualizar_Click"
CommandName="visualizar" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
<HeaderStyle Width="70px" />
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="66px" HeaderText="ALTERAR">
<ItemTemplate>
<asp:Button ID="Btn_Alterar" runat="server" Text="ALTERAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana, Arial"
CommandName="editar" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
<HeaderStyle Width="66px" />
</asp:TemplateField>
<asp:TemplateField HeaderStyle-Width="66px" HeaderText="FEEDBACK">
<ItemTemplate>
<asp:Button ID="Btn_Feedback" runat="server" Text="ADICIONAR" CssClass="Btn_Grid" Font-Size="7pt" Font-Names="Verdana,Arial"
CommandName="feedback" CommandArgument="<%# ((GridViewRow)Container).RowIndex %>" />
</ItemTemplate>
<HeaderStyle Width="66px" />
</asp:TemplateField>
</columns>
<EditRowStyle ForeColor="Black" CssClass="GridViewEditRow" />
<FooterStyle BackColor="#CCCCCC" />
<HeaderStyle BackColor="Black" Font-Bold="True" ForeColor="White" BorderColor="White" BorderStyle="Solid" BorderWidth="1px" />
<PagerSettings Mode="NumericFirstLast" FirstPageText="First" LastPageText="Last" PageButtonCount="5" />
<PagerStyle BackColor="#CCCCCC" ForeColor="Black" HorizontalAlign="Left" />
<RowStyle BackColor="White" />
<SelectedRowStyle BackColor="#000099" Font-Bold="True" ForeColor="White" />
</asp:GridView>
CodeBehind:
public partial class TodosChamados : System.Web.UI.Page
{
BDUsuarios usr = new BDUsuarios();
BDFuncionalidades func = new BDFuncionalidades();
BDChamados ch = new BDChamados();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = ch.BuscaTodosChamados();
GridView1.DataBind();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.Cells[1].Text == "ALTA")
{
e.Row.Cells[1].BackColor = System.Drawing.Color.Red;
e.Row.ControlStyle.Font.Bold = true;
}
}
if (e.Row.Cells[0].Visible = e.Row.RowType == DataControlRowType.Pager)
{
e.Row.Cells[0].Visible = false;
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName != "Sort")
{
if (e.CommandName == "visualizar")
{
Session["id"] = GridView1.Rows[Convert.ToInt32(e.CommandArgument.ToString())].Cells[0].Text;
Session["editar"] = null;
}
else if (e.CommandName == "editar")
{
Session["id"] = GridView1.Rows[Convert.ToInt32(e.CommandArgument.ToString())].Cells[0].Text; //Grava o ID do chamado da linha correspondente.
Session["editar"] = 1; // 1 - Editar 2 - Não Editar .
}
else if (e.CommandName == "feedback")
{
Session["id"] = GridView1.Rows[Convert.ToInt32(e.CommandArgument.ToString())].Cells[0].Text; //Grava o ID do chamado da linha correspondente.
Response.Redirect("~/Adm/Feedback.aspx");
}
Response.Redirect("~/Adm/DetalhesChamado.aspx");
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = ch.BuscaTodosChamados();
GridView1.DataBind();
}
Update 2
Now i hopefully have found the reason for your pager not being shown. You are making the first colum invisible, even for the pager-row in RowDataBound, but the pager is sitting in the first cell by default:
e.Row.Cells[0].Visible = false;
You have to check the correct RowType:
e.Row.Cells[0].Visible = e.Row.RowType == DataControlRowType.Pager;
or even better on the aspx markup:
<asp:BoundField HeaderText="ID" DataField="id" Visible="False" />
A silly question, have you set AllowPaging to true?
<asp:GridView Id="GridView1" runat="server" AllowPaging="True" >
<PagerSettings Mode="NumericFirstLast" FirstPageText="First" LastPageText="Last" PageButtonCount="5" />
</asp:gridview>
GridView.AllowPaging Property
true if the paging feature is enabled; otherwise, false. The default is false.
You should also databind the GridView only if(!IsPostBack) when viwstate is enabled(default).
So wrap your databind code from Page_Load(i guess) into this check:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
GridView1.DataSource = ch.BuscaTodosChamados();
GridView1.DataBind();
}
}
Otherwise events won't be triggered and changes will be overwritten when you reload data on postback.
Update According to your last edit:
I assume that your RowCommand is the reason for this issue. It is called before the PageIndexChanging event and it is triggered also when the page changes(if i remember correctly). So have a look at your Response.Redirect which happens when no if/else-if will catch it which seems to be the case.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName != "Sort")
{
if (e.CommandName == "visualizar")
{
// ..
}
else if (e.CommandName == "editar")
{
//..
}
else if (e.CommandName == "feedback")
{
//..
}
Response.Redirect("~/Adm/DetalhesChamado.aspx");
}
}
You must specify the event for OnPageIndexChanging in your .aspx. It should be:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
OnPageIndexChanging = "GridView1_PageIndexChanging"
AutoGenerateColumns="False" DataKeyNames="LastName,FirstName"
EnablePersistedSelection="True" SelectedRowStyle-BackColor="Yellow"
DataSourceID="SqlDataSource1" AllowSorting="True">
You might be having the same problem here
UPDATE
Make sure that the data that's being bound to the GridView is more that 5 since PageSize="5". If the number of rows is less than 5, then the pager will not be shown.

passing an ID between pages

I have a Default.aspx page in which I have bind a Grid. In the Grid is a button named Details.
I also have a Details.aspx which has a GridView. If I click the button that exist in Default.aspx, there appears an Details.aspx page which appears empty.
When click the Detail button of a specific row, there appears the details of that button clicked. I am not understanding on how to pass the ID to Details.aspx.
Can anybody guide me to this please?
Details.aspx
<asp:GridView ID="DetailsGridView" runat="server" BackColor="White" AutoGenerateColumns="false"
BorderColor="#DEDFDE" BorderStyle="None" BorderWidth="1px" CellPadding="4" DataKeyNames="ID"
ForeColor="Black" GridLines="Vertical">
<FooterStyle BackColor="#CCCC99" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
Default.aspx:
<Columns>
<asp:BoundField HeaderText="First Name" DataField="FirstName" />
<asp:BoundField HeaderText="Last Name" DataField = "LastName" />
<asp:BoundField HeaderText="HomePhoneNumber" DataField="HomePhoneNumber" />
<asp:TemplateField HeaderText="ViewDetails">
<ItemTemplate>
<asp:Button ID="Deatils" runat="server" Text="Details" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Actions">
<ItemTemplate>
<asp:Button ID="Modify" runat="server" Text="Modify" />
<asp:Button ID="Delete" runat="server" Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#CCCC99" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
</asp:GridView>
</div>
JavaScript
<script type="text/javascript">
function viewProfile(index)
{
var GridID = document.getElementById("PersonGridView");
var row=GridID.rows[parseInt(index)+1];
window.open('Details.aspx?coaid'+row);
}
</script>
Code Behind of Default.aspx:
protected void PersonGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var DataKeys = PersonGridView.DataKeys[e.Row.RowIndex];
DataKeys.Value.ToString();
var ID = DataKeys["ID"].ToString();
Button btnDetails = (Button)e.Row.FindControl("Deatils");
Button btnModify = (Button)e.Row.FindControl("Modify");
Button btnDelete = (Button)e.Row.FindControl("Delete");
btnModify.CommandName = "Modify";
btnDelete.CommandName = "Delete";
btnDetails.CommandName = "Deatils";
btnDelete.CommandArgument = btnModify.CommandArgument = btnDetails.CommandArgument = string.Format("{0}", ID);
btnDetails.Attributes["onclick"] = string.Format("viewProfile({0}); return false;", e.Row.RowIndex);
}
}
EDIT: I've modified my example to not use a HyperLink and instead will build a LinkButton that can navigate to your Details.aspx page passing the ID value in the QueryString:
Default.aspx:
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton CommandName="Details" CommandArgument='<%# Eval("ID") %>' Text="Details" runat="server" />
</ItemTemplate>
</asp:TemplateField>
Default.aspx.cs:
protected void PersonGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Details")
{
Server.Transfer("Details.aspx?ID=" + e.CommandArgument.ToString());
}
}
On the Grid when you click the button
do the following
public protected sub Button_Click(EventArgs e)
{
if (grid.SelectedItem != null)
{
var selectedRow = grid.SelectedItem ;
// do what ever you want to Selected Row that may be binding it to another Form etc.
}
Do the same for OnSelectedEvent if you want to do it that way instead.
public protected sub OnSelectedEvent_Click(EventArgs e)
{
if (grid.SelectedItem != null)
{
var selectedRow = grid.SelectedItem ;
// do what ever you want to Selected Row that may be binding it to another Form etc.
}

gridview postback not being posted - VS2008

This is my aspx:
<asp:UpdatePanel ID="resultPanel" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="AddDocument" />
</Triggers>
<ContentTemplate>
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="False" EnableSortingAndPagingCallbacks="True"
AllowPaging="True" DataSourceID="FilesObjectDataSource" PageSize="5" OnRowCommand="gridView_RowCommand"
DataKeyNames="FileGuid" HorizontalAlign="Left" Width="100%" BorderStyle="Solid"
BorderColor="Black">
<Columns>
<asp:BoundField DataField="RID" HeaderText="ID" ReadOnly="True"></asp:BoundField>
<asp:BoundField DataField="Category" HeaderText="SubCategory" ReadOnly="True">
</asp:BoundField>
<asp:BoundField DataField="FileTypeName" HeaderText="Type" ReadOnly="True">
</asp:BoundField>
<asp:BoundField DataField="FileGUID" Visible="false" />
<asp:ButtonField Text="X" ButtonType="Button" ItemStyle-Width="20px" CommandName="DelFile">
<ItemStyle Width="20px" />
</asp:ButtonField>
</Columns>
<RowStyle CssClass="RowStyle" />
<EmptyDataRowStyle CssClass="EmptyRowStyle" />
<PagerStyle CssClass="PagerStyle" />
<SelectedRowStyle CssClass="SelectedRowStyle" />
<HeaderStyle CssClass="HeaderStyle" />
<EditRowStyle CssClass="EditRowStyle" />
<AlternatingRowStyle CssClass="AltRowStyle" />
</asp:GridView>
</ContentTemplate>
This is my code behind for the ButtonField marked 'X'
protected void gridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DelFile")
{
//Selected Row
int rowIndex = Convert.ToInt32(e.CommandArgument);
fileGuid = new Guid(gridView.DataKeys[rowIndex].Values["FileGuid"].ToString());
}
}
Sometimes itt results in object ref not set and at times it works. Not sure why this happens in production and not in dev and testing.
I'm not sure if it makes any difference, but but the case in ("FileGuid")
DataKeyNames="FileGuid"
and
fileGuid = new Guid(gridView.DataKeys[rowIndex].Values["FileGuid"].ToString());
doesn't match ("FileGUID")
<asp:BoundField DataField="FileGUID" Visible="false" />
You can use like this for accessing value at row command event
protected void gridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DelFile")
{
int index = Convert.ToInt32(e.CommandArgument);
int documentID = Convert.ToInt32(gridView.DataKeys[index].Value);
// Write your further code
}
}

Resources