Using identifier in gridview - c#

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.

Related

Edit on child gridview collapse the expansion

I have a parent grid GVInvoiceDet. CRUD operation on this grid is working fine. In each row of the parent, I have child grid GVTaxDetails which opens on click of image ie expand/collapse feature.
I am looking for CRUD within child grid also. But when I click on edit within child, the texbox for editing doesn't appear and the parent grid collapses.
Here is child grid rowediting code
protected void GVTaxDetails_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView gvTemp = (GridView)sender;
gvUniqueID = gvTemp.UniqueID;
//gvEditIndex = e.NewEditIndex;
gvTemp.EditIndex = e.NewEditIndex;
GVInvoiceDet.DataBind();
}
Parent row editing code
protected void GVInvoiceDet_RowEditing(object sender, GridViewEditEventArgs e)
{
GVInvoiceDet.EditIndex = e.NewEditIndex;
GVInvoiceDet.DataBind();
BindItemGrid();
}
ASPX file :
<asp:GridView ID="GVInvoiceDet" runat="server" Width="100%" AutoGenerateColumns="False"
HorizontalAlign="Left" BorderStyle="Outset" OnRowCancelingEdit="GVInvoiceDet_RowCancelingEdit"
OnRowEditing="GVInvoiceDet_RowEditing" OnRowDataBound="GVInvoiceDet_RowDataBound" ShowFooter="True"
OnRowCommand="GVInvoiceDet_RowCommand" OnRowUpdating="GVInvoiceDet_RowUpdating"
OnRowDeleting="GVInvoiceDet_RowDeleting" OnRowDeleted="GVInvoiceDet_RowDeleted"
OnRowUpdated="GVInvoiceDet_RowUpdated" AllowSorting="True" DataSourceID="DSItemGrid" DataKeyNames="invoiceno,itemcd">
<HeaderStyle BackColor="#0000ff" ForeColor="Yellow" />
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<EditRowStyle BackColor="#FFFFCC" ForeColor="#330099" />
<AlternatingRowStyle BackColor="#FE9CD5" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
<a href="javascript:expandcollapse('div<%# Eval("itemcd") %>', 'one');">
<img id="imgdiv<%# Eval("itemcd") %>" alt="Click to show/hide Tax Details <%# Eval("itemcd") %>" border="0" src="Images/plus.png" />
</a>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="10%" HeaderText="Item Code" SortExpression="itemcd">
<ItemTemplate>
<asp:Label ID="lblItemCode" runat="server" Text='<%# Eval("itemcd")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtItemCode" Width="90%" runat="server" Text='<%# Eval("itemcd")%>' Enabled="false"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtItemCode" Width="90%" runat="server" Text='' Enabled="false"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="10%" HeaderText="HSN Code" SortExpression="hsncd">
<ItemTemplate>
<asp:Label ID="lblItemHSNCode" runat="server" Text='<%# Eval("hsncd")%>'></asp:Label><asp:HiddenField ID="hdnItemGST" runat="server" Value='<%# Eval("itempercentage") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtItemHSN" Width="90%" runat="server" Text='<%# Eval("hsncd")%>' Enabled="false"></asp:TextBox><asp:HiddenField ID="hdnEditItemGST" runat="server" Value='<%# Eval("itempercentage") %>' />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtItemHSN" Width="90%" runat="server" Text='' Enabled="false"></asp:TextBox><asp:HiddenField ID="hdnFooterItemGST" runat="server" Value='<%# Eval("itempercentage") %>' />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="25%" HeaderText="Item Description" SortExpression="itemdesc">
<ItemTemplate>
<asp:Label ID="lblItemDesc" runat="server" Text='<%# Eval("itemdesc")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblItemDesc" runat="server" Text='<%# Eval("itemdesc")%>' Visible="false"></asp:Label><asp:HiddenField ID="hdnItemDesc" runat="server" Value='<%# String.Format("{0}-{1}-{2}",Eval("itemcd"),Eval("hsncd"),Eval("itempercentage")) %>' />
<asp:DropDownList ID="eddlItemDesc" runat="server" AutoPostBack="true" OnSelectedIndexChanged="eddlItemDesc_SelectedIndexChanged"></asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="fddlItemDesc" runat="server" AutoPostBack="true" OnSelectedIndexChanged="fddlItemDesc_SelectedIndexChanged"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="5%" HeaderText="Quantity">
<ItemTemplate>
<asp:Label ID="lblItemQty" runat="server" Text='<%# Eval("quantity")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtItemQty" Width="90%" runat="server" Text='<%# Eval("quantity")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtItemQty" Width="90%" MaxLength="100" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="5%" HeaderText="Unit Rate">
<ItemTemplate>
<asp:Label ID="lblItemUnitRate" runat="server" Text='<%# Eval("unitrate")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtItemUnitRate" Width="90%" runat="server" Text='<%# Eval("unitrate")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtItemUnitRate" Width="90%" MaxLength="100" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="5%" HeaderText="Unit Value">
<ItemTemplate>
<asp:Label ID="lblItemUnitValue" runat="server" Text='<%# Eval("unitvalue")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtItemUnitValue" Width="90%" runat="server" Text='<%# Eval("unitvalue")%>' Enabled="false"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtItemUnitValue" Width="90%" MaxLength="100" runat="server" Enabled="false"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="5%" HeaderText="Final Value">
<ItemTemplate>
<asp:Label ID="lblItemFinalValue" runat="server" Text=''></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtItemFinalValue" Width="90%" runat="server" Text='' Enabled="false"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtItemFinalValue" Width="90%" MaxLength="100" runat="server" Enabled="false"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" HeaderText="Edit" />
<asp:TemplateField HeaderText="Delete" ItemStyle-Width="5%">
<ItemTemplate>
<asp:LinkButton ID="linkDeleteInvoiceItem" CommandName="DeleteItem" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="linkAddInvoiceItem" CommandName="AddItem" runat="server">Add</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<tr>
<td colspan="100%">
<div id="div<%# Eval("itemcd") %>" style="display: none; position: relative; left: 15px; overflow: auto; width: 97%">
<asp:GridView ID="GVTaxDetails" BackColor="White" Width="100%" Font-Size="Small" AutoGenerateColumns="false"
runat="server" DataKeyNames="invoiceno,itemcd,valuecd" ShowFooter="True" OnRowUpdating="GVTaxDetails_RowUpdating"
OnRowCommand="GVTaxDetails_RowCommand" OnRowEditing="GVTaxDetails_RowEditing" GridLines="None"
OnRowUpdated="GVTaxDetails_RowUpdated" OnRowCancelingEdit="GVTaxDetails_CancelingEdit"
OnRowDataBound="GVTaxDetails_RowDataBound" OnRowDeleting="GVTaxDetails_RowDeleting" OnRowDeleted="GVTaxDetails_RowDeleted"
ShowHeaderWhenEmpty="true" BorderStyle="Double" BorderColor="#0083C1">
<RowStyle BackColor="Gainsboro" />
<AlternatingRowStyle BackColor="White" />
<HeaderStyle BackColor="#0083C1" ForeColor="White" />
<FooterStyle BackColor="White" />
<Columns>
<asp:TemplateField ItemStyle-Width="5%" HeaderText="SL No">
<ItemTemplate>
<asp:Label ID="lblViewTaxSlno" runat="server" Text='<%# Eval("slno")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtViewTaxSlno" runat="server" Text='<%# Eval("slno")%>' Enabled="false"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtViewTaxSlno" MaxLength="3" Width="80%" runat="server" Text='<%# Convert.ToInt32(Container.DataItemIndex) + 1 %>' Enabled="false"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="15%" HeaderText="Value">
<ItemTemplate>
<asp:HiddenField ID="hdnViewTaxDesc" runat="server" Value='<%# Eval("valuecd") %>' />
<asp:Label ID="lblViewTaxDesc" runat="server" Text='<%# Eval("valuedesc")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:HiddenField ID="hdnViewTaxDesc" runat="server" Value='<%# Eval("valuecd") %>' />
<asp:DropDownList ID="eddlViewTaxDesc" Width="90%" runat="server" AutoPostBack="true" OnSelectedIndexChanged="eddViewTaxDesc_SelectedIndexChanged"></asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:HiddenField ID="hdnViewTaxDesc" runat="server" Value='<%# Eval("valuecd") %>' />
<asp:DropDownList ID="fddViewTaxDesc" Width="90%" runat="server" OnSelectedIndexChanged="fddlViewTaxDesc_SelectedIndexChanged"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="3%" HeaderText="Amount">
<ItemTemplate>
<asp:Label ID="lblViewTaxAmount" runat="server" Text='<%# Eval("value")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtViewTaxAmount" runat="server" Text='<%# Eval("value")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtViewTaxAmount" runat="server" Text='<%# Eval("value")%>'></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="7%" HeaderText="Ref. Sl No">
<ItemTemplate>
<asp:Label ID="lblViewTaxRefNo" runat="server" Text='<%# Eval("refslno")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:HiddenField ID="hdnViewTaxRefNo" runat="server" Value='<%# Eval("refslno") %>' />
<asp:DropDownList ID="eddlViewTaxRefNo" Width="90%" runat="server" AutoPostBack="false"></asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="fddViewTaxRefNo" Width="90%" runat="server" AutoPostBack="false"></asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="10%" HeaderText="Tax-Mode">
<ItemTemplate>
<asp:Label ID="lblViewTaxMode" runat="server" Text='<%# Eval("absper").ToString()=="A"?"Absolute":"Percentage"%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:HiddenField ID="hdnViewTaxMode" runat="server" Value='<%# Eval("absper") %>' />
<asp:DropDownList ID="eddlViewTaxMode" Width="90%" runat="server" AutoPostBack="false">
<asp:ListItem Value="-1" Text="-Select Mode-" Selected="True"></asp:ListItem>
<asp:ListItem Value="A" Text="Absolute"></asp:ListItem>
<asp:ListItem Value="P" Text="Percentage"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="fddlViewTaxMode" Width="95%" runat="server" AutoPostBack="false">
<asp:ListItem Value="-1" Text="-Select Mode-" Selected="True"></asp:ListItem>
<asp:ListItem Value="A" Text="Absolute"></asp:ListItem>
<asp:ListItem Value="P" Text="Percentage"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="10%" HeaderText="Operation">
<ItemTemplate>
<asp:Label ID="lblViewTaxOperation" runat="server" Text='<%# Eval("addsub").ToString()=="A"?"Add":"Subtract"%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:HiddenField ID="hdnViewTaxOperation" runat="server" Value='<%# Eval("addsub") %>' />
<asp:DropDownList ID="eddlViewTaxOperation" Width="90%" runat="server" AutoPostBack="false">
<asp:ListItem Value="-1" Text="-Select Operation-" Selected="True"></asp:ListItem>
<asp:ListItem Value="A" Text="Add"></asp:ListItem>
<asp:ListItem Value="S" Text="Subtract"></asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="fddlViewTaxOperation" Width="90%" runat="server" AutoPostBack="false">
<asp:ListItem Value="-1" Text="-Select Operation-" Selected="True"></asp:ListItem>
<asp:ListItem Value="A" Text="Add"></asp:ListItem>
<asp:ListItem Value="S" Text="Subtract"></asp:ListItem>
</asp:DropDownList>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="3%" HeaderText="Final Amount">
<ItemTemplate>
<asp:Label ID="lblViewTaxFinalAmount" runat="server" Text='<%# Eval("finalvalue")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtViewTaxFinalAmount" runat="server" Text='<%# Eval("finalvalue")%>' Enabled="false"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtViewTaxFinalAmount" runat="server" Text='<%# Eval("finalvalue")%>' Enabled="false"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField HeaderText="Edit" ShowEditButton="True" />
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton ID="linkDeleteTaxDetails" CommandName="Delete" runat="server">Delete</asp:LinkButton>
</ItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="linkAddTaxDetails" CommandName="AddTax" runat="server">Add</asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="DSItemGrid" runat="server" ConnectionString="<%$ ConnectionStrings:GSTCS %>" ProviderName="<%$ ConnectionStrings:GSTCS.ProviderName %>"
SelectCommand="select invoiceno, dt.itemcd itemcd, mast.itemdesc itemdesc, mast.hsncd hsncd, dt.quantity quantity,
mast.unitrate unitrate, dt.unitvalue unitvalue, mast.itempercentage itempercentage
from GSTINVOICEDT dt join GSTITEMMASTER mast on (dt.itemcd = mast.itemcd and dt.unitcode = mast.unitcode and dt.projectcode = mast.projectcode)
where dt.unitcode = :unitCode and dt.projectCode = :projCode and dt.invoiceno = :invoiceNo order by invoiceno, itemcd">
<SelectParameters>
<asp:SessionParameter DefaultValue="05" Name="unitCode" SessionField="unit" />
<asp:SessionParameter DefaultValue="0501" Name="projCode" SessionField="project" />
<asp:SessionParameter DefaultValue="INVOICENO" Name="invoiceNo" SessionField="invoiceNo" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
I got the work done... Posting the code for others if come across similar situation.
In parent rowdatabound have added code to keep the div open and update the editIndex.
protected void GVInvoiceDet_RowDataBound(object sender, GridViewRowEventArgs e) {
GridViewRow row = e.Row;
if(row.RowType == DataControlRowType.Header)
{
return;
}
else if (row.RowType == DataControlRowType.DataRow )
{
//Find Child GridView control
GridView gvTax = new GridView();
gvTax = (GridView)row.FindControl("GVTaxDetails");
if (gvTax.UniqueID == gvUniqueID)
{
gvTax.EditIndex = gvEditIndex;
//Expand the Child grid
ClientScript.RegisterStartupScript(GetType(), "Expand", "<SCRIPT LANGUAGE='javascript'>expandcollapse('div" + ((DataRowView)e.Row.DataItem)["itemcd"].ToString() + "','one');</script>");
}
}
}
expandcollapse is function on aspx side:
function expandcollapse(obj, row) {
var div = document.getElementById(obj);
var img = document.getElementById('img' + obj);
if (div.style.display == "none") {
div.style.display = "block";
if (row == 'alt') {
img.src = "Images/minus.png";
}
else {
img.src = "Images/minus.png";
}
img.alt = "Close View Taxes";
}
else {
div.style.display = "none";
if (row == 'alt') {
img.src = "Images/plus.png";
}
else {
img.src = "Images/plus.png";
}
img.alt = "Expand View Taxes";
}
}

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];

Sorting Gridview not working with Linq

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

While Editing the GridView, dropdownlist values are not storing in the variable

values of selected items in dropdownlist(edit gridview) are returning NULL. It should return selected values..
Code in aspx.cs file::
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
DropDownList ct = (DropDownList)row.FindControl("DropDownList6");
string ctype = ct.SelectedItem.Text;
string sql1 = ("Select Case_Type_Value FROM Case_Type where Case_Type_Text ='" + ctype + "' ");
DropDownList cs = (DropDownList)row.FindControl("DropDownList3");
string cstatus = cs.SelectedItem.Text;
string sql2 = ("Select Case_Status_Value FROM Case_Status where Case_Status_Text ='" + cstatus + "' ");
SqlConnection con= new SqlConnection(ConfigurationManager.ConnectionStrings["con"].ToString());
SqlCommand cmd1 = new SqlCommand(sql1, con);
SqlCommand cmd2 = new SqlCommand(sql2, con);
con.Open();
int v1 = Convert.ToInt32(cmd1.ExecuteScalar());
int v2 = Convert.ToInt32(cmd2.ExecuteScalar());
con.Close();
SqlCommand cmd = new SqlCommand("UPDATE Table SET Case_Type = #Case_Type, Case_Status = #Case_Status, con);
cmd.Parameters.AddWithValue("#Case_Type", v1);
cmd.Parameters.AddWithValue("#Case_Status", v2);
Below is the aspx code for the page:
<asp:GridView ID="GridView1" runat="server" CellPadding="5" ForeColor="#333333" width="1000px"
GridLines="None" OnPageIndexChanging="gridView_PageIndexChanging"
AllowSorting="True" OnSorting="gridView_Sorting" AutoGenerateColumns="False" OnRowUpdating="GridView1_RowUpdating"
BorderStyle="Outset" CellSpacing="1" Font-Names="Cambria"
Font-Size="Small" AllowPaging="True" ShowFooter="True"
ShowHeaderWhenEmpty="True"
DataSourceID="SqlDataSource1" onselectedindexchanged="GridView1_SelectedIndexChanged"
>
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:TemplateField HeaderText="Case Number" SortExpression="case_number">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("case_number") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label7" runat="server" Text='<%# Bind("case_number") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Case Name" SortExpression="case_name">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("case_name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label8" runat="server" Text='<%# Bind("case_name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Case Type" SortExpression="Case_Type_Text">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList6" runat="server"
DataSourceID="SqlDataSource2" DataTextField="Case_Type_Text"
DataValueField="Case_Type_Text" SelectedValue='<%# Bind("Case_Type_Text") %>'>
<asp:ListItem>--Select--</asp:ListItem>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label9" runat="server" Text='<%# Bind("Case_Type_Text") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Case Status" SortExpression="Case_Status_Text">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList3" runat="server"
DataSourceID="SqlDataSource3" DataTextField="Case_Status_Text" DataValueField="Case_Status_Text"
SelectedValue='<%# Bind("Case_Status_Text") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Case_Status_Text") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Assigned Date" SortExpression="assigned_date">
<EditItemTemplate>
<asp:TextBox ID="TextBox5" runat="server"
Text='<%# Bind("assigned_date", "{0:d}") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label10" runat="server"
Text='<%# Bind("assigned_date", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Assigned To" SortExpression="assigned_to">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList7" runat="server"
DataSourceID="SqlDataSource4" DataTextField="User_Name"
DataValueField="User_Name" SelectedValue='<%# Bind("assigned_to") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label11" runat="server" Text='<%# Bind("assigned_to") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Withdrawn" SortExpression="date_withdrawn">
<EditItemTemplate>
<cc1:DatePicker ID="DatePicker5" runat="server" DateFormat="yyyy-MM-dd"
CalendarDate='<%# Bind("date_withdrawn") %>' TextCssClass="" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label4" runat="server"
Text='<%# Bind("date_withdrawn", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Delivered" SortExpression="date_delivered">
<EditItemTemplate>
<cc1:DatePicker ID="DatePicker7" runat="server"
CalendarDate='<%# Bind("date_delivered") %>' TextCssClass=""
/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label6" runat="server"
Text='<%# Bind("date_delivered", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="QC By" SortExpression="qc_by">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList5" runat="server"
DataSourceID="SqlDataSource4" DataTextField="User_Name" DataValueField="User_Name"
SelectedValue='<%# Bind("qc_by") %>'>
</asp:DropDownList>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("qc_by") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="QC Date" SortExpression="qc_date">
<EditItemTemplate>
<cc1:DatePicker ID="DatePicker6" runat="server"
CalendarDate='<%# Bind("qc_date") %>' TextCssClass=""
/>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label5" runat="server" Text='<%# Bind("qc_date", "{0:d}") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Additional Notes">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"
Text='<%# Bind("additional_notes") %>' TextMode="MultiLine"></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("additional_notes") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="True" ButtonType="Button"
CausesValidation="False" />
</Columns>
<EditRowStyle BackColor="#999999" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
Try likes this ,
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
DropDownList ct = (DropDownList)row.Cells[2].FindControl("DropDownList6");
string ctype = ct.SelectedValue;
DropDownList cs = (DropDownList)row.Cell[3].FindControl("DropDownList3");
string cstatus = cs.SelectedValue;
GridViewRow row = grdVw.Rows[e.RowIndex];
String str = Convert.ToString(((DropDownList)(row.Cells[2].Controls[0])).SelectedItem);
Get your cell number ,Numbering for cells start from zero so it will be 2 for DropDownList6 in your code .
Please check and verify if it works !

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