Sorting Gridview not working with Linq - c#

Hi and thanks in advance,
I am trying to sort a gridview with linq and nothing is happening. I am not getting an error, but no sorting is happening in the view either. I am also using firebug for debugging as well.
asp:
<asp:GridView ID="GridViewRangeSetup" runat="server" AllowSorting="True" OnSorting="Gridview_Sort"
PagerStyle-Mode="NumericPages" AutoGenerateColumns="false" Width="100%" CssClass="gridView"
OnPageIndexChanging="GridViewRangeSetup_PageIndexChanging" AllowPaging="True"
PageSize="20" DataKeyNames="RangeId" OnRowCommand="GridViewRangeSetup_RowCommand"
OnRowEditing="GridViewRangeSetup_RowEditing" OnRowCancelingEdit="GridViewRangeSetup_CancelEditRow"
OnRowUpdating="GridViewRangeSetup_UpdateRow" OnRowDataBound="GridViewRangeSetup_RowDataBound">
<RowStyle CssClass="rowStyle"></RowStyle>
<HeaderStyle CssClass="headerBar" ForeColor="#ffffff"></HeaderStyle>
<AlternatingRowStyle CssClass="altRow" />
<Columns>
<asp:TemplateField HeaderText="Edit" HeaderStyle-Width="5%" HeaderStyle-ForeColor="#f2f2f2"
HeaderStyle-Font-Bold="false" HeaderStyle-Font-Size="Small">
<ItemTemplate>
<asp:ImageButton ID="imgEdit" runat="server" ImageUrl="~/images/icon_edit.png" CausesValidation="false"
CommandArgument='<%#Eval("RangeId") %>' CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="imgUpdate" runat="server" ImageUrl="~/images/icon_update.png"
CausesValidation="false" CommandArgument='<%#Eval("RangeId") %>' CommandName="Update" />
<asp:ImageButton ID="ImageCancel" runat="server" ImageUrl="~/images/icon_cancel.png"
CausesValidation="false" CommandArgument='<%#Eval("RangeId") %>' CommandName="Cancel" />
</EditItemTemplate>
<HeaderStyle Font-Bold="False" Font-Size="Small" ForeColor="#F2F2F2" Width="5%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete" HeaderStyle-Width="3%" HeaderStyle-ForeColor="#f2f2f2"
HeaderStyle-Font-Bold="false" HeaderStyle-Font-Size="Small">
<ItemTemplate>
<asp:ImageButton ID="imgDelete" runat="server" CausesValidation="false" OnClientClick="return DeleleAlert();"
CommandArgument='<%#Eval("RangeId") %>' CommandName="Remove" ImageUrl="~/images/icon_delete.png" />
</ItemTemplate>
<HeaderStyle Font-Bold="False" Font-Size="Small" ForeColor="#F2F2F2" Width="3%" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Description" SortExpression="Description">
<EditItemTemplate>
<asp:TextBox ID="txtDescription" runat="server" CssClass="textbox" Text='<%# Eval("Description") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblDescription" runat="server" Text='<%# Eval("Description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Country" SortExpression="Country.CountryName">
<EditItemTemplate>
<asp:DropDownList ID="ddlCountry" runat="server" CssClass="dropdown" AutoPostBack="True"
AppendDataBoundItems="true" DataTextField="CountryName" DataValueField="CountryId">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Bind("CountryName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="State/Province" SortExpression="GeographicRegion.RegionName">
<EditItemTemplate>
<asp:DropDownList ID="ddlRegion" runat="server" CssClass="dropdown" AutoPostBack="True"
AppendDataBoundItems="true" DataTextField="RegionName" DataValueField="GeographicRegionId">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblRegion" runat="server" Text='<%# Bind("RegionName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Base/Facility" SortExpression="Base.BaseName">
<EditItemTemplate>
<asp:DropDownList ID="ddlFacility" runat="server" CssClass="dropdown" AutoPostBack="True"
AppendDataBoundItems="true" DataTextField="BaseName" DataValueField="BaseId">
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblFacility" runat="server" Text='<%# Bind("BaseName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Map Name" SortExpression="RangeMap.MapName">
<EditItemTemplate>
<asp:TextBox ID="txtMapName" runat="server" CssClass="textbox" Text='<%# Eval("MapName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblMapName" runat="server" Text='<%# Eval("MapName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Map">
<HeaderStyle HorizontalAlign="center" />
<ItemTemplate>
<asp:HyperLink ID="HyperLink_Map1" runat="server" NavigateUrl='<%# DataBinder.Eval(Container.DataItem,"MapPath") %>'
Text="">
<asp:Image ID="Image1" runat="server" ImageUrl='<%# DataBinder.Eval(Container.DataItem,"MapPath") %>'
Width="50px" Height="50px" />
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Low Latitude" SortExpression="RangeMap.LowLat">
<EditItemTemplate>
<asp:TextBox ID="txtLowLat" runat="server" CssClass="textbox" Text='<%# Eval("LowLat") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblLowLat" runat="server" Text='<%# Eval("LowLat") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Low Longitude" SortExpression="RangeMap.LowLong">
<EditItemTemplate>
<asp:TextBox ID="txtLowLong" runat="server" CssClass="textbox" Text='<%# Eval("LowLong") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblLowLong" runat="server" Text='<%# Eval("LowLong") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="High Latitude" SortExpression="RangeMap.HighLat">
<EditItemTemplate>
<asp:TextBox ID="txtHighLat" runat="server" CssClass="textbox" Text='<%# Eval("HighLat") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblHighLat" runat="server" Text='<%# Eval("HighLat") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="High Longitude" SortExpression="RangeMap.HighLong">
<EditItemTemplate>
<asp:TextBox ID="txtHighLong" runat="server" CssClass="textbox" Text='<%# Eval("HighLong") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblHighLong" runat="server" Text='<%# Eval("HighLong") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<asp:Button ID="RangeSetup_Status" CssClass="page-btn blue" CausesValidation="false"
CommandArgument='<%#Eval("RangeId") %> ' runat="server" Text="Status" OnClick="btnRangeStatus_Click">
</asp:Button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
c#
protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
{
//Label2.Text = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
String column = e.SortExpression;
IQueryable<dynamic> sortedGridview = ConvertSortDirectionToSql(e.SortDirection) == "ASC" ?
(from r in context.Ranges.AsEnumerable()
where r.isDeleted == false
orderby typeof(WISSModel.Range).GetProperty(column).GetValue(r, null) ascending
select new
{
r.RangeId,
r.Description,
r.Country.CountryName,
r.GeographicRegion.RegionName,
r.Base.BaseName,
r.RangeMap.MapName,
r.RangeMap.MapPath,
r.RangeMap.LowLat,
r.RangeMap.LowLong,
r.RangeMap.HighLat,
r.RangeMap.HighLong
}).AsQueryable<dynamic>() :
(from r in context.Ranges.AsEnumerable()
where r.isDeleted == false
orderby typeof(WISSModel.Range).GetProperty(column).GetValue(r, null) descending
select new
{
r.RangeId,
r.Description,
r.Country.CountryName,
r.GeographicRegion.RegionName,
r.Base.BaseName,
r.RangeMap.MapName,
r.RangeMap.MapPath,
r.RangeMap.LowLat,
r.RangeMap.LowLong,
r.RangeMap.HighLat,
r.RangeMap.HighLong
}).AsQueryable<dynamic>();
//var sortedGridview = context.Ranges.Where("it.isDeleted == false").OrderBy(column);
GridViewRangeSetup.DataSource = sortedGridview.ToList();
//var test = sortedGridview.ToList();
//System.Diagnostics.Debugger.Break();
GridViewRangeSetup.DataBind();
}

Looks like it is not allowed to code order by parameters in string like in dynamic T-SQL. You should replace yout LINQ query with this one to make it work:
String column = e.SortExpression;
IQueryable<dynamic> sortedGridview = ConvertSortDirectionToSql(e.SortDirection) == "ASC" ?
(from r in context.Ranges
where r.isDeleted == false
orderby typeof(Range).GetProperty(column).GetValue(r,null) ascending
select new
{
r.RangeId,
Description = r.Description,
CountryName = r.Country.CountryName,
RegionName = r.GeographicRegion.RegionName,
BaseName = r.Base.BaseName,
r.RangeMap.MapName,
r.RangeMap.MapPath,
r.RangeMap.LowLat,
r.RangeMap.LowLong,
r.RangeMap.HighLat,
r.RangeMap.HighLong
}).AsQueryable<dynamic>() :
(from r in context.Ranges
where r.isDeleted == false
orderby typeof(Range).GetProperty(column).GetValue(r, null) descending
select new
{
r.RangeId,
Description = r.Description,
CountryName = r.Country.CountryName,
RegionName = r.GeographicRegion.RegionName,
BaseName = r.Base.BaseName,
r.RangeMap.MapName,
r.RangeMap.MapPath,
r.RangeMap.LowLat,
r.RangeMap.LowLong,
r.RangeMap.HighLat,
r.RangeMap.HighLong
}).AsQueryable<dynamic>();

Found another solution:
Using the DataSetLinqOperators class and modifying it slightly to allow null values:
protected void Gridview_Sort(object sender, GridViewSortEventArgs e)
{
WISSModel.WISSEntities context = new WISSModel.WISSEntities();
var sortedGridview = (from r in context.Ranges
where r.isDeleted == false
select new
{
r.RangeId,
r.Description,
r.Country.CountryName,
r.GeographicRegion.RegionName,
r.Base.BaseName,
r.RangeMap.MapName,
r.RangeMap.MapPath,
r.RangeMap.LowLat,
r.RangeMap.LowLong,
r.RangeMap.HighLat,
r.RangeMap.HighLong
}).ToList();
DataTable sortedTable = sortedGridview.CopyToDataTable();
sortedTable.DefaultView.Sort = e.SortExpression + " " + ConvertSortDirectionToSql(e.SortDirection);
GridViewRangeSetup.DataSource = sortedTable;
GridViewRangeSetup.DataBind();
}
private string ConvertSortDirectionToSql(SortDirection sortDirection)
{
string newSortDirection = String.Empty;
int sort = (int)ViewState["Sort"];
switch (sort)
{
case 0:
newSortDirection = "ASC";
ViewState["Sort"] = 1;
break;
case 1:
newSortDirection = "DESC";
ViewState["Sort"] = 0;
break;
}
return newSortDirection;
}

Related

Understanding Gridview RowCommand

I've coded a gridview that doesn't fire when I click the edit button and I found an older question that addresses my issue by just using e.CommandName with if statements under the RowCommand method. I'm trying to figure out how to implement it with my code.
My question is, how do I use e.RowIndex during update to find my controls and reference those now? Also, I've tried calling my old Update method but it won't let me use sender and e as parameters because GridviewCommandEventArgs is different from GridViewEventUpdateArgs. I'm pretty lost, any help would be appreciated in straightening this out.
C#:
void RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if (e.CommandName == "Edit")
{
}
if (e.CommandName == "Update")
{
UpdateCustomer(sender, e);
string nFirstName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtFirstName")).Text;
string nLastName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtLastName")).Text;
string nEmergency = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEmergency")).Text;
string nCell = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCell")).Text;
string nAge = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtAge")).Text;
string nActivityCard = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtActivityCard")).Text;
string nBoat = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtBoat")).Text;
string nInitials = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtInitials")).Text;
string nGroup = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtGroup")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Person set FirstName=#FirstName, LastName=#LastName, " +
"Emergency#=#Emergency, Cell#=#Cell, Age=#Age, ActivityCard=#ActivityCard, Initials=#Initials, CraftType=#Boat, Group#=#Group " +
"where Person.PersonID=#Pid;" +
"SELECT Person.PersonID, Person.FirstName AS FirstName, Person.LastName AS LastName, Person.Emergency# AS Emergency#, Person.Cell# AS Cell#, Person.Age AS Age, " +
"Person.ActivityCard AS ActivityCard, Person.CraftType AS CraftType, Person.Initials AS Initials, Person.Group# AS Group# " +
"FROM Person INNER JOIN " +
"TripSchedule ON Person.PersonID = TripSchedule.PersonID where TripSchedule.Date = #Date and " +
"TripSchedule.Time = #Time and TripSchedule.TripType = #Type order by Person.Group#;";
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = nFirstName;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = nLastName;
cmd.Parameters.Add("#Emergency", SqlDbType.NChar).Value = nEmergency;
cmd.Parameters.Add("#Cell", SqlDbType.NChar).Value = nCell;
cmd.Parameters.Add("#Age", SqlDbType.NChar).Value = nAge;
cmd.Parameters.Add("#ActivityCard", SqlDbType.NChar).Value = nActivityCard;
cmd.Parameters.Add("#Initials", SqlDbType.NChar).Value = nInitials;
cmd.Parameters.Add("#Boat", SqlDbType.VarChar).Value = nBoat;
cmd.Parameters.Add("#Group", SqlDbType.VarChar).Value = nGroup;
cmd.Parameters.AddWithValue("#Date", TextBox1.Text);
cmd.Parameters.AddWithValue("#Time", ddlTripTime.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Type", ddlTripType.SelectedItem.ToString());
long personID = long.Parse(GridView1.DataKeys[e.RowIndex].Values["PersonID"].ToString());
cmd.Parameters.AddWithValue("#Pid", personID);
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
if (e.CommandName == "Cancel")
{
}
}
ASP.NET:
<div id="dvGrid" style="padding: 0px">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" DataKeyNames="PersonID" runat="server" AutoGenerateColumns="False"
Font-Names="Arial" Font-Size="10pt" AlternatingRowStyle-BackColor="blue" HeaderStyle-BackColor="aqua"
ShowFooter="true" OnRowEditing="EditCustomer" OnRowUpdating="UpdateCustomer"
OnRowCancelingEdit="CancelEdit" ShowHeaderWhenEmpty="true" Height="95px">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Height="20px" Text='<%# Eval("FirstName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName")%>'></asp:TextBox>
</EditItemTemplate>
<ItemStyle Width = "60px" />
<FooterTemplate>
<asp:TextBox ID="txtFirstName" width="60px" MaxLength="15" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%# Eval("LastName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" Text='<%#Bind("LastName")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLastName" width="60px" MaxLength="15" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<asp:Label ID="lblAge" runat="server" Text='<%# Eval("Age")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAge" Width="30px" MaxLength="2" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Activity Card">
<ItemTemplate>
<asp:Label ID="lblActivityCard" runat="server" Text='<%# Eval("ActivityCard")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtActivityCard" runat="server" Text='<%# Eval("ActivityCard")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtActivityCard" Width="50px" MaxLength="7" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cell Phone">
<ItemTemplate>
<asp:Label ID="lblCell" runat="server" Text='<%# Eval("Cell#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCell" runat="server" Text='<%# Eval("Cell#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCell" Width="70px" MaxLength="10" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emergency Phone">
<ItemTemplate>
<asp:Label ID="lblEmergency" runat="server" Text='<%# Eval("Emergency#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmergency" runat="server" Text='<%# Eval("Emergency#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmergency" width="70px" MaxLength="10" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Boat Type">
<ItemTemplate>
<asp:Label ID="lblBoat" runat="server" Text='<%# Eval("CraftType")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBoat" runat="server" Text='<%# Eval("CraftType")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtBoat" Width="80px" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Initials">
<ItemTemplate>
<asp:Label ID="lblInitials" runat="server" Text='<%# Eval("Initials")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtInitials" runat="server" Text='<%# Eval("Initials")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtInitials" width="30px" MaxLength="2" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Group #">
<ItemTemplate>
<asp:Label ID="lblGroup" runat="server" Text='<%# Eval("Group#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtGroup" runat="server" Text='<%# Eval("Group#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtGroup" MaxLength="2" Width="20px" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server" CommandArgument='<%# Eval("PersonID")%>'
OnClientClick="return confirm('Are you sure you want to delete?')" Text="Delete"
OnClick="DeleteCustomer"></asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Submit" OnClick="AddNewCustomer" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" CommandName="Edit">Edit</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update">Update</asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel">Cancel</asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You can pass RowIndex as CommandArgument for your LinkButtons.
<EditItemTemplate>
<asp:LinkButton ID="lnkUpdate" runat="server" CommandName="Update" CommandArgument='<%# Container.DataItemIndex %>'>Update</asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CommandName="Cancel" CommandArgument='<%# Container.DataItemIndex %>'>Cancel</asp:LinkButton>
</EditItemTemplate>
Which can be access from code behind. Using rowindex you can get hold of the current row and find any controls using FindControl
void RowCommand(Object sender, GridViewCommandEventArgs e)
{
int rowindex = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Update")
{
....
}
if (e.CommandName == "Cancel")
{
....
}
}
e.CommandArgument will contain the index of the row clicked, so you can access the relevant controls via
int index = Convert.ToInt32(e.CommandArgument);
GridView1.Rows[index].Controls[x];

Using identifier in gridview

I have a gridview that has insert, update, and delete functionality. On my update statement, I'm not sure how to set my identifier PersonID = to the currently selected identifier in the gridview that is being updated. Is there a common method that people use to achieve this functionality?
Code for Asp.net GRIDVIEW
<div id="dvGrid" style="padding: 0px">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
Font-Names="Arial" Font-Size="10pt" AlternatingRowStyle-BackColor="blue" HeaderStyle-BackColor="aqua"
ShowFooter="true" OnRowEditing="EditCustomer" OnRowUpdating="UpdateCustomer"
OnRowCancelingEdit="CancelEdit" Height="95px">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Height="20px" Text='<%# Eval("FirstName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtFirstName" width="60px" MaxLength="15" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%# Eval("LastName")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtLastName" width="60px" MaxLength="15" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Age">
<ItemTemplate>
<asp:Label ID="lblAge" runat="server" Text='<%# Eval("Age")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAge" Width="30px" MaxLength="2" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Activity Card">
<ItemTemplate>
<asp:Label ID="lblActivityCard" runat="server" Text='<%# Eval("ActivityCard")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtActivityCard" runat="server" Text='<%# Eval("ActivityCard")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtActivityCard" Width="50px" MaxLength="7" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cell Phone">
<ItemTemplate>
<asp:Label ID="lblCell" runat="server" Text='<%# Eval("Cell#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtCell" runat="server" Text='<%# Eval("Cell#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCell" Width="70px" MaxLength="10" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Emergency Phone">
<ItemTemplate>
<asp:Label ID="lblEmergency" runat="server" Text='<%# Eval("Emergency#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmergency" runat="server" Text='<%# Eval("Emergency#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtEmergency" width="70px" MaxLength="10" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Boat Type">
<ItemTemplate>
<asp:Label ID="lblBoat" runat="server" Text='<%# Eval("CraftType")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBoat" runat="server" Text='<%# Eval("CraftType")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtBoat" Width="80px" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Initials">
<ItemTemplate>
<asp:Label ID="lblInitials" runat="server" Text='<%# Eval("Initials")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtInitials" runat="server" Text='<%# Eval("Initials")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtInitials" width="30px" MaxLength="2" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Group #">
<ItemTemplate>
<asp:Label ID="lblGroup" runat="server" Text='<%# Eval("Group#")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtGroup" runat="server" Text='<%# Eval("Group#")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtGroup" MaxLength="2" Width="20px" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkRemove" runat="server" CommandArgument='<%# Eval("PersonID")%>'
OnClientClick="return confirm('Are you sure you want to delete?')" Text="Delete"
OnClick="DeleteCustomer"></asp:LinkButton>
</itemtemplate>
<FooterTemplate>
<asp:Button ID="btnAdd" runat="server" Text="Submit" OnClick="AddNewCustomer" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" />
</Columns>
<AlternatingRowStyle BackColor="#C2D69B" />
<HeaderStyle BackColor="Aqua" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView1" />
</Triggers>
</asp:UpdatePanel>
</div>
Method for Update:
protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e)
{
string nFirstName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtFirstName")).Text;
string nLastName = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtLastName")).Text;
string nEmergency = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtEmergency")).Text;
string nCell = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtCell")).Text;
string nAge = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtAge")).Text;
string nActivityCard = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtActivityCard")).Text;
string nBoat = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtBoat")).Text;
string nInitials = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtInitials")).Text;
string nGroup = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("txtGroup")).Text;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "update Person set FirstName=#FirstName, LastName=#LastName, " +
"Emergency#=#Emergency, Cell#=#Cell, Age=#Age, ActivityCard=#ActivityCard, Initials=#Initials, CraftType=#Boat, Group#=#Group " +
"where Person.PersonID=Person.PersonID;" +
"SELECT Person.PersonID, Person.FirstName AS FirstName, Person.LastName AS LastName, Person.Emergency# AS Emergency#, Person.Cell# AS Cell#, Person.Age AS Age, " +
"Person.ActivityCard AS ActivityCard, Person.CraftType AS CraftType, Person.Initials AS Initials, Person.Group# AS Group# " +
"FROM Person INNER JOIN " +
"TripSchedule ON Person.PersonID = TripSchedule.PersonID where TripSchedule.Date = #Date and " +
"TripSchedule.Time = #Time and TripSchedule.TripType = #Type order by Person.Group#;";
cmd.Parameters.Add("#FirstName", SqlDbType.VarChar).Value = nFirstName;
cmd.Parameters.Add("#LastName", SqlDbType.VarChar).Value = nLastName;
cmd.Parameters.Add("#Emergency", SqlDbType.NChar).Value = nEmergency;
cmd.Parameters.Add("#Cell", SqlDbType.NChar).Value = nCell;
cmd.Parameters.Add("#Age", SqlDbType.NChar).Value = nAge;
cmd.Parameters.Add("#ActivityCard", SqlDbType.NChar).Value = nActivityCard;
cmd.Parameters.Add("#Initials", SqlDbType.NChar).Value = nInitials;
cmd.Parameters.Add("#Boat", SqlDbType.VarChar).Value = nBoat;
cmd.Parameters.Add("#Group", SqlDbType.VarChar).Value = nGroup;
cmd.Parameters.AddWithValue("#Date", TextBox1.Text);
cmd.Parameters.AddWithValue("#Time", ddlTripTime.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#Type", ddlTripType.SelectedItem.ToString());
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
First specify DataKeyNames="PersonID" for your gridview definition.
Here is how you get the PersonID value in your UpdateCustomer function in code behind.
protected void UpdateCustomer(object sender, GridViewUpdateEventArgs e)
{
// assuming that the value of your PersonID is numeric value
long personID = long.Parse(GridView1.DataKeys[e.RowIndex].Values["PersonID"].ToString());
....
}
The personID value you can pass as an argument to your WHERE clause.
Alternatively you can declare a HiddenField in your gridview and bind PersonID which you can access in you UpdateCustomer function using FindControl method.

How can I dynamically edit gridview data?

How to edit and delete fields in a gridview, not connected with database and gridview is being populated with data entered by a user in the textboxes? Also, how can I remove the row using delete button in the gridview?
this is my grid view in ASP page :
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CssClass="mGrid"
ShowFooter="True" ShowHeaderWhenEmpty="True" Width="70%" OnRowDataBound="GridView1_RowDataBound"
OnRowCommand="GridView1_RowCommand" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<AlternatingRowStyle CssClass="alt" />
<Columns>
<asp:TemplateField HeaderText="Item Code">
<EditItemTemplate>
<asp:TextBox ID="txtItemCode" runat="server" Text='<%# Bind("ItemCode") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="ItemCode" runat="server" Text='<%# Bind("ItemCode") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Product">
<EditItemTemplate>
<asp:TextBox ID="txtProduct" runat="server" Text='<%# Bind("Product") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Product" runat="server" Text='<%# Bind("Product") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Unit Price">
<EditItemTemplate>
<asp:TextBox ID="txtUnitPrice" runat="server" Text='<%# Bind("UnitPrice") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="UnitPrice" runat="server" Text='<%# Bind("UnitPrice") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Batch">
<EditItemTemplate>
<asp:TextBox ID="txtBatch" runat="server" Text='<%# Bind("Batch") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Batch" runat="server" Text='<%# Bind("Batch") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField FooterText="Total" HeaderText="Expiary Date">
<EditItemTemplate>
<asp:TextBox ID="txtExpiaryDate" runat="server" Text='<%# Bind("ExpiaryDate") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="ExpiaryDate" runat="server" Text='<%# Bind("ExpiaryDate") %>'></asp:Label>
</ItemTemplate>
<FooterStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity">
<EditItemTemplate>
<asp:TextBox ID="txtQuantity" runat="server" Text='<%# Bind("Quantity") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Quantity" runat="server" Text='<%# Eval("Quantity") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="GetQuantity" runat="server" Text='<%# GetQuantity() %>'></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Total">
<ItemTemplate>
<asp:Label ID="Total" runat="server" Text='<%# Eval("Total") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="GetTotal" runat="server" Text='<%# GetTotal() %>'></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ButtonType="Image" DeleteImageUrl="~/Images/delete.png" EditImageUrl="~/Images/edit.png"
HeaderText="EDIT" ShowDeleteButton="True" ShowEditButton="True" />
</Columns>
<FooterStyle BackColor="Gainsboro" ForeColor="Black" />
<PagerStyle CssClass="pgr" HorizontalAlign="Right" />
</asp:GridView>
I'm using this code to add data to the grid.
protected void btnAdd_Click(object sender, EventArgs e)
{
if (ViewState["CurrentData"] != null)
{
var dt = (DataTable)ViewState["CurrentData"];
var count = dt.Rows.Count;
BindGrid(count);
}
else
{
BindGrid(1);
}
Clear();
}
private void BindGrid(int rowcount)
{
var DataTbl = new DataTable();
DataRow DataRw;
DataTbl.Columns.Add("ItemCode", typeof(String));
DataTbl.Columns.Add("Product", typeof(String));
DataTbl.Columns.Add("UnitPrice", typeof(String));
DataTbl.Columns.Add("Batch", typeof(String));
DataTbl.Columns.Add("ExpiaryDate", typeof(String));
DataTbl.Columns.Add("Quantity", typeof(double));
DataTbl.Columns.Add("Total", typeof(double));
if (ViewState["CurrentData"] != null)
{
for (var i = 0; i < rowcount + 1; i++)
{
DataTbl = (DataTable)ViewState["CurrentData"];
if (DataTbl.Rows.Count > 0)
{
DataRw = DataTbl.NewRow();
DataRw[0] = DataTbl.Rows[0][0].ToString();
}
}
DataRw = DataTbl.NewRow();
DataRw[0] = txtItemCode.Text;
DataRw[1] = ddlProduct.SelectedItem;
DataRw[2] = txtUnitPrice.Text;
DataRw[3] = txtBatch.Text;
DataRw[4] = txtExpiaryDate.Text;
DataRw[5] = txtQty.Text;
DataRw[6] = (Convert.ToInt32(Convert.ToDouble(
txtUnitPrice.Text) * Convert.ToDouble(
txtQty.Text)) - ((Convert.ToDouble(
txtUnitPrice.Text) * Convert.ToDouble(
txtQty.Text))) * Convert.ToDouble(
txtProductDiscount.Text) / 100).ToString();
DataTbl.Rows.Add(DataRw);
}
else
{
DataRw = DataTbl.NewRow();
DataRw[0] = txtItemCode.Text;
DataRw[1] = ddlProduct.SelectedItem;
DataRw[2] = txtUnitPrice.Text;
DataRw[3] = txtBatch.Text;
DataRw[4] = txtExpiaryDate.Text;
DataRw[5] = txtQty.Text;
DataRw[6] = (Convert.ToInt32(Convert.ToDouble(
txtUnitPrice.Text) * Convert.ToDouble(
txtQty.Text)) - ((Convert.ToDouble(
txtUnitPrice.Text) * Convert.ToDouble(
txtQty.Text))) * Convert.ToDouble(
txtProductDiscount.Text) / 100).ToString();
DataTbl.Rows.Add(DataRw);
}
if (ViewState["CurrentData"] != null)
{
GridView1.DataSource = (DataTable)ViewState["CurrentData"];
GridView1.DataBind();
}
else
{
GridView1.DataSource = DataTbl;
GridView1.DataBind();
}
ViewState["CurrentData"] = DataTbl;
}
First of all your code and query is not clear.
if i am understanding it right then the problem in your code is that data is not deleting or updating.
as i saw in your code, you are holding data in view state. please recheck your code at the stage of GridView1_RowUpdating() and GridView1_RowCommand() (hoping you are using this for delete) events. after deleting/updating the data you should update the view state also.

Gridview not showing records?

I just attached linq data to gridview it is not showing row ?
DataDataContext db = new DataDataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
BindData();
}
private void BindData()
{
var source = from n in db.Names
select n;
gridSample.DataSource = source.ToList<Name>();
gridSample.DataBind();'
}
<asp:UpdatePanel ID="panelGrid" runat="server">
<ContentTemplate>
<asp:GridView runat="server" ID="gridSample" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="First Name">
<EditItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" Text='<%Bind("FirstName") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" ID="lblFirstName" Text='<%Eval("FirstName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<EditItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" Text='<%Bind("LastName") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" ID="lblLastName" Text='<%Eval("LastName") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date of Birth">
<EditItemTemplate>
<asp:TextBox ID="txtDOB" runat="server" Text='<%Bind("DOB") %>' />
</EditItemTemplate>
<ItemTemplate>
<asp:Label runat="server" ID="lblDOB" Text='<%Eval("DOB") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
Try this
List<Name> source = (from n in db.Names select n).ToList();
gridSample.DataSource = source;
gridSample.DataBind();'
<asp:TextBox ID="txtFirstName" runat="server" Text='<%# Bind("FirstName") %>' />
try this:
private void BindData()
{
var source = from n in db.Names
select n;
gridSample.DataSource = source;
gridSample.DataBind();'
}
Regards
Set the property
AutoPostBack = True
for the GridView. Since it is inside the UpdatePanel.

I can not find the controls of lblCategoryName and ddlBlogCategoty the Edit button click in Gridview

How can I find the controls lblCategoryName and ddlBlogCategory?
Here is my code:
protected void grdRetailStore_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblAccount = (Label)e.Row.FindControl("lblCategoryName");
string s = lblAccount.Text;
DropDownList ddlBlogCategory = (DropDownList)e.Row.FindControl("ddlBlogCategoty");
DAO.DAO dao_category = new DAO.DAO();
DataTable dt_blog_cat = dao_category.SelectCategory();
if (ddlBlogCategory != null)
{
// ddlBlogCategory.Items.Clear();
ddlBlogCategory.DataSource = dao_category.SelectCategory();
ddlBlogCategory.DataTextField = "CategoryName";
ddlBlogCategory.DataValueField = "BlogCategoryID";
ddlBlogCategory.DataBind();
}
}
}
<asp:GridView ID="grdRetailStore" runat="server" AutoGenerateColumns="false" DataKeyNames="PortalId" OnRowEditing="grdRetailStore_RowEditing"
OnRowCancelingEdit="grdRetailStore_RowCancelingEdit" OnRowDataBound="grdRetailStore_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="ID">
<HeaderStyle Width="100px" Wrap="False" />
<EditItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Bind("PortalId") %>'></asp:Label>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Bind("PortalId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="AdvertiserName">
<HeaderStyle Width="100px" Wrap="False" />
<EditItemTemplate>
<asp:TextBox ID="txtAdvName" runat="server" Text='<%# Bind("AdvertiserName") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblAdvName" runat="server" Text='<%# Bind("AdvertiserName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PromoCategory">
<HeaderStyle Width="100px" Wrap="False" />
<EditItemTemplate>
<%-- <asp:DropDownList ID="" runat="server" DataTextField="Account_Name" DataValueField="Account_Id"
AppendDataBoundItems="true">
<%-- <asp:ListItem Selected="True" Text="---Select---" Value="0"></asp:ListItem></asp:DropDownList> --%>
<asp:TextBox ID="txtPromoCat" runat="server" Text='<%# Bind("PromoCatId") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblPromoCat" runat="server" Text='<%# Bind("PromoCatId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Start Date">
<HeaderStyle Width="100px" Wrap="False" />
<EditItemTemplate>
<asp:TextBox ID="txtPromostartdate" runat="server" Text='<%# Bind("PromoStartDate") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblPromostartdate" runat="server" Text='<%# Bind("PromoStartDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="End Date">
<HeaderStyle Width="100px" Wrap="False" />
<EditItemTemplate>
<asp:TextBox ID="txtPromoenddate" runat="server" Text='<%# Bind("PromoEndDate") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblPromoenddate" runat="server" Text='<%# Bind("PromoEndDate") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Html Code">
<HeaderStyle Width="100px" Wrap="False" />
<EditItemTemplate>
<asp:TextBox ID="txtHtml" runat="server" Text='<%# Bind("HtmlCode") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblHtml" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CategoryName">
<HeaderStyle Width="100px" Wrap="False" />
<EditItemTemplate>
<asp:DropDownList ID="ddlBlogCategoty" runat="server" DataTextField="CategoryName" DataValueField="BlogCategoryID"
AppendDataBoundItems="true">
<asp:ListItem Selected="True" Text="---Select---" Value="0"></asp:ListItem></asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="lblCategoryName" runat="server" Text='<%# Bind("CategoryName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="False">
<HeaderStyle Width="100px" Wrap="False" />
<EditItemTemplate>
<asp:LinkButton ID="lbkUpdate" runat="server" CausesValidation="True" CommandName="Update"
Text="Update" OnClientClick="return ValidateUpdate();"></asp:LinkButton>
<asp:LinkButton ID="lnkCancel" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="lnkEdit" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Change your code behind and include check of RowState.
protected void grdRetailStore_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState == DataControlRowState.Normal)
{
Label lblAccount = (Label)e.Row.FindControl("lblCategoryName");
string s = lblAccount.Text;
}
if (e.Row.RowState == DataControlRowState.Edit)
{
DropDownList ddlBlogCategory = (DropDownList)e.Row.FindControl("ddlBlogCategoty");
if (ddlBlogCategory != null)
{
// ddlBlogCategory.Items.Clear();
ddlBlogCategory.DataSource = dao_category.SelectCategory();
ddlBlogCategory.DataTextField = "CategoryName";
ddlBlogCategory.DataValueField = "BlogCategoryID";
ddlBlogCategory.DataBind();
}
}
DAO.DAO dao_category = new DAO.DAO();
DataTable dt_blog_cat = dao_category.SelectCategory();
}
}

Categories

Resources