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];
Related
I have an editable GridView but I would also like to have an add new row functionality, so I made a button using FooterTemplate for all editable fields and set CommandName="AddNew" . Everything looks as expected on the front end, but Add New Row cannot find txtGrantId, txtPotId or txtBudget at all and throws System.NullReferenceException 'Object reference not set to an instance of an object.'. The issue has to be in the code behind, but I am attaching the front end as well. The data source is pretty long but it does call OnRowCommand="gvPotsMoneyGrants_RowCommand"
ASPX
<%--Primary Key LinkId--%>
<asp:TemplateField HeaderText="LinkId" SortExpression="LinkId">
<ItemTemplate>
<asp:Label ID="lblLinkId" runat="server" Text='<%# Eval("LinkId") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<%--GrantId--%>
<asp:TemplateField HeaderText="GrantId" SortExpression="GrantId">
<ItemTemplate>
<asp:Label ID="lblGrantIdMain" runat="server" Text='<%#Eval("GrantId") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtGrantId" runat="server" Text='<%#Bind("GrantId") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="inGrantId" Width="120px" runat="server" />
<asp:RequiredFieldValidator ID="vGrantId" runat="server" ControlToValidate="inGrantId" Text="?" ValidationGroup="VG5" />
</FooterTemplate>
</asp:TemplateField>
<%--PotId--%>
<asp:TemplateField HeaderText="PotId" SortExpression="PotId">
<ItemTemplate>
<asp:Label ID="lblPotIdMain" runat="server" Text='<%#Eval("PotId") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtPotId" runat="server" Text='<%#Bind("PotId") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="inPotId" Width="120px" runat="server" />
<asp:RequiredFieldValidator ID="vPotId" runat="server" ControlToValidate="inPotId" Text="?" ValidationGroup="VG5" />
</FooterTemplate>
</asp:TemplateField>
<%--Budget--%>
<asp:TemplateField HeaderText="Budget" SortExpression="Budget">
<ItemTemplate>
<asp:Label ID="lblBudgetMain" runat="server" Text='<%#Eval("Budget") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBudget" runat="server" Text='<%#Bind("Budget") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="inBudget" Width="120px" runat="server" />
<asp:RequiredFieldValidator ID="vBudget" runat="server" ControlToValidate="inBudget" Text="?" ValidationGroup="VG5" />
</FooterTemplate>
</asp:TemplateField>
Code behind
protected void gvPotsMoneyGrants_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox txtGrantId = (TextBox)gvPotsMoneyGrants.FooterRow.FindControl("txtGrantId");
TextBox txtPotId = (TextBox)gvPotsMoneyGrants.FooterRow.FindControl("txtPotId");
TextBox txtBudget = (TextBox)gvPotsMoneyGrants.FooterRow.FindControl("txtBudget");
string GrantId, PotId, Budget;
GrantId = txtGrantId.Text;
PotId = txtPotId.Text;
Budget = txtBudget.Text;
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("GrantId", GrantId);
cmd.Parameters.AddWithValue("PotId", PotId);
cmd.Parameters.AddWithValue("Budget", Budget);
}
}
Please, try the code below.
protected void gvPotsMoneyGrants_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("AddNew"))
{
TextBox inGrantId = (TextBox)gvPotsMoneyGrants.FooterRow.FindControl("inGrantId");
TextBox inPotId = (TextBox)gvPotsMoneyGrants.FooterRow.FindControl("inPotId");
TextBox inBudget = (TextBox)gvPotsMoneyGrants.FooterRow.FindControl("inBudget");
string GrantId, PotId, Budget;
GrantId = inGrantId.Text;
PotId = inPotId.Text;
Budget = inBudget.Text;
SqlCommand cmd = new SqlCommand();
cmd.Parameters.AddWithValue("GrantId", GrantId);
cmd.Parameters.AddWithValue("PotId", PotId);
cmd.Parameters.AddWithValue("Budget", Budget);
}
}
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.
I have a grid view it has 3 drop down lists and 3 text boxes in template field. On the top of the grid view i have two text boxes( text box 1 and 2) which initilize there values when page is loaded. i also have 3 buttons for add new row , save , search. I want my grid view to show data from database when search button is clicked i.e select * from table where text box 1 and 2 equal to some thing. My HTML looks like.
AutoGenerateColumns="false" onselectedindexchanged="Gridview1_SelectedIndexChanged" BackColor="White"
BorderColor="#336666" BorderStyle="Double" BorderWidth="3px" CellPadding="4"
GridLines="Horizontal">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Item name">
<ItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" Height="25px" Width="119px"
DataTextField = "Item_name" Text='<%# Bind("Item_name") %>' DataValueField="Item_name"
AppendDataBoundItems="true">
</asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sub item">
<ItemTemplate>
<asp:DropDownList ID="DropDownList2" runat="server" Height="25px" Width="119px"
AppendDataBoundItems="true"
DataValueField = "Sub_item" Text='<%# DataBinder.Eval(Container, "DataItem.Sub_item") %>' DataTextField = "Sub_item"
/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Location">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Location") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Permit number">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Permit no") %>' ></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Applied">
<ItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server"
Height="25px" Width="119px"
DataTextField="Text" AppendDataBoundItems="true" Text='<%# DataBinder.Eval(Container, "DataItem.Applied") %>' DataValueField="Value" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Revision">
<ItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.Revision") %>' ></asp:TextBox>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonSave" runat="server" Text="Save" OnClick="Save_Click" />
<asp:Button ID="ButtonAdd" runat="server" Text="Add Row" />
<asp:Button ID="search" runat="server" Text="Search" OnClick="Search_Click"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
on my search button click i have this code
if (TextBox4.Text != null && TextBox5.Text != null)
{
string job = TextBox4.Text.ToString();
string leg = TextBox5.Text.ToString();
string connString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
using (var conn = new SqlConnection(connString))
using (var cmd = conn.CreateCommand())
{
Response.Write(job);
Response.Write(leg);
conn.Open();
SqlCommand comand = new SqlCommand("SELECT * from Billing_heads where job# = '" + job + "' AND leg#='" + leg + "' ", conn);
// try
//{
SqlDataAdapter adp = new SqlDataAdapter(comand);
DataSet ds = new DataSet();
adp.Fill(ds);
//gvPros is the ID of GridView.
Gridview1.DataSource = ds;
Gridview1.DataBind();
Please help me that how can i bind my gridview because in Text='<%# Bind("Item_name") %>' property it saying the column name it says property with name "coloumn name " does not exists please help
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;
}
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();
}
}