Grid view edit - drop down list issue - asp.net

I have a grid view and i'm trying to create a drop down list in the edit mode of the grid view.
The grid view show the users in my project and i want the drop down list let them change their city from the cities table in my database.
I have tried to do using a Template editing according to a video i saw on youtube(https://www.youtube.com/watch?v=YB2pe_C2Tbg&t=191s&ab_channel=MukeshChaudhary). Although, i'm getting the error:
System.Data.OleDb.OleDbException: 'You cannot add or change a record
because a related record is required in table 'cities'.'
Code behind
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using RapidTyper.App_Code;
public partial class ManagerChange : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack) PopulateGrid();
}
private DataSet GetData()
{
UserService UserService = new UserService();
return UserService.GetUsers();
}
private void PopulateGrid()
{
GridView1.DataSource = GetData();
GridView1.DataBind();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
PopulateGrid();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
PopulateGrid();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
User userDetaling = new User();
userDetaling.setFName(((TextBox)GridView1.Rows[e.RowIndex].Cells[0].Controls[0]).Text);
userDetaling.setLName(((TextBox)GridView1.Rows[e.RowIndex].Cells[1].Controls[0]).Text);
userDetaling.setID(GridView1.Rows[e.RowIndex].Cells[2].Text);
userDetaling.setBirthDate(((TextBox)GridView1.Rows[e.RowIndex].Cells[3].Controls[0]).Text);
userDetaling.setAddress(((TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0]).Text);
userDetaling.setZipCode (((TextBox)GridView1.Rows[e.RowIndex].Cells[6].Controls[0]).Text);
userDetaling.setEmail(((TextBox)GridView1.Rows[e.RowIndex].Cells[7].Controls[0]).Text);
userDetaling.setPassword(((TextBox)GridView1.Rows[e.RowIndex].Cells[8].Controls[0]).Text);
UserService UserService = new UserService();
UserService.UpdateUser(userDetaling);
GridView1.EditIndex = -1;
PopulateGrid();
}
}
Aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" style="margin-top: 21px">
<Columns>
<asp:BoundField DataField="fName" HeaderText="Name" />
<asp:BoundField DataField="lName" HeaderText="Last Name" />
<asp:BoundField DataField="ID" HeaderText="ID" ReadOnly="True" />
<asp:BoundField DataField="birthDate" HeaderText="Birth Date" />
<asp:TemplateField HeaderText="city">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" DataSourceID="SqlDataSource1" DataTextField="cityName" DataValueField="cityNum">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" ProviderName="<%$ ConnectionStrings:ConnectionString.ProviderName %>" SelectCommand="SELECT * FROM [cities]"></asp:SqlDataSource>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("cityName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="address" HeaderText="address" />
<asp:BoundField DataField="zipcode" HeaderText="zip code" />
<asp:BoundField DataField="email" HeaderText="email" />
<asp:BoundField DataField="userPassword" HeaderText="password" />
<asp:CommandField ButtonType="Button" HeaderText="Edit" ShowEditButton="True" />
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>

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

strange behaviour when I click on a newpage in gridview acts like I have clicked a row

first my html
<asp:GridView ID="GridViewCustomers" runat="server" AutoGenerateColumns="False"
AllowPaging="True" datakeynames="Reservation_ID,Excursion_ID"
onpageindexchanging="GridViewCustomers_PageIndexChanging"
onrowcommand="GridViewCustomers_SelectedIndexChanged"
BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" GridLines="Horizontal" >
<AlternatingRowStyle BackColor="#F7F7F7" />
<Columns>
<asp:CommandField ShowSelectButton="True" />
<asp:BoundField DataField="Reservation_ID" HeaderText="РЕЗ. №" />
<asp:BoundField DataField="Name" HeaderText="Име на Екскурзия" />
<asp:BoundField DataField="Reservation_TotalAmount" HeaderText="Сума по резервацията" />
<asp:BoundField DataField="Excursion_ID" Visible="false" />
<asp:BoundField DataField="ReservationDate" HeaderText="Дата на заминаване" />
<asp:TemplateField HeaderText="Имена на Туристи">
<ItemTemplate>
<asp:Repeater ID="Repeater1" runat="server" DataSource='<%# Eval("TouristName") %>'>
<ItemTemplate>
<%# (Container.ItemIndex+1)+"."+ Container.DataItem %><br />
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<SortedAscendingCellStyle BackColor="#F4F4FD" />
<SortedAscendingHeaderStyle BackColor="#5A4C9D" />
<SortedDescendingCellStyle BackColor="#D8D8F0" />
<SortedDescendingHeaderStyle BackColor="#3E3277" />
</asp:GridView>
So in the code you will se that on a click on select button I get the value od datakeyna and redirect the user to another page. The problem is that when I click page 2 of my gridview i'm redirected to the other page as if I have selected one row.
protected void Page_Init(object sender, EventArgs e)
{
this.lstUserReservations.AddRange(lstUserReservations);
this.lstUserReservations.AddRange(lstUserReservations);
this.lstUserReservations.AddRange(lstUserReservations);
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
User_Reservation trr = new User_Reservation();
lstUserReservations = new List<User_Reservation>();
lstUserReservations = LoadReservationsForUser();
GridViewCustomers.DataSource = lstUserReservations;
GridViewCustomers.DataBind();
}
}
protected void GridViewCustomers_SelectedIndexChanged(object sender, GridViewCommandEventArgs e)
{ int indexer = Int32.Parse(e.CommandArgument.ToString());
Session["еxcursion_id"] = this.GridViewCustomers.DataKeys[indexer].Values["Excursion_ID"].ToString();
Response.Redirect("ReservationInfo.aspx");
}
protected void GridViewCustomers_PageIndexChanging(object sender,
System.Web.UI.WebControls.GridViewPageEventArgs e)
{
this.GridViewCustomers.PageIndex = e.NewPageIndex;
this.GridViewCustomers.DataBind();
}
}
Yousee that I have
There is a slight code you have to take care of. If you are changing the paging, then check if you have clicked the paging and return if you have or else select the row. Also, when you change the paging, the RowCommand event works first and after that PageIndexChanging event.
protected void GridViewCustomers_SelectedIndexChanged(object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "Page")
return;
int indexer = Int32.Parse(e.CommandArgument.ToString());
Session["еxcursion_id"] = this.GridViewCustomers.DataKeys[indexer].Values["Excursion_ID"].ToString();
Response.Redirect("ReservationInfo.aspx");
}
Let me know if this had worked for you.

how to disable a linkbutton from a gridview

<asp:GridView ID="GridView1" class="datagrid" runat="server" AutoGenerateColumns="False" width="90%" Height="400px"
OnRowCommand="GridView1_RowCommand" BackColor="White"
BorderColor="#CC9966" BorderStyle="None"
BorderWidth="1px" CellPadding="4">
<Columns>
<asp:TemplateField HeaderText="File" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server"
CausesValidation="False"
CommandArgument='<%# Eval("File") %>'
CommandName="Download" Text='<%# Eval("File") %>'
onclick="LinkButton1_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Size" HeaderText="Size in Bytes" />
<asp:BoundField DataField="Type" HeaderText="File Type" />
</Columns>
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<HeaderStyle BackColor="#990000" Font-Bold="True"
ForeColor="#FFFFCC" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099"
HorizontalAlign="Center" />
<RowStyle BackColor="White" ForeColor="#330099" />
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True"
ForeColor="#663399" />
<SortedAscendingCellStyle BackColor="#FEFCEB" />
<SortedAscendingHeaderStyle BackColor="#AF0101" />
<SortedDescendingCellStyle BackColor="#F6F0C0" />
<SortedDescendingHeaderStyle BackColor="#7E0000" />
</asp:GridView>
i have this download function and upload
i want to include a download verification code where there will be a textbox and button if the characters from textbox is incorrect download will be disable.
please note that in the file section i have the linkbutton that enables the user to download the file
Try the code below, should be written in code behind file:
protected void GrivView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
LinkButtton lbtn = new LinkButtton();
lbtn = (LinkButton)e.Row.FindControl("LinkButton1");
lbtn.Enable = false;
}
I think this line of code is enough
((LinkButton)e.Row.Cells[1].Controls[0]).Visible = false;
In this way we can disable or enable linkbutton or any other control dynamically
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGrid();
/*if (<condtition)
* {
* */
GridView1.Columns[3].Visible = false;
// * }
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//make it again visible
GridView1.Columns[3].Visible = true;
// code to edit the rows
}

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.

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