How to hide EditItemTemplate controls while exporting Gridview - c#

This is my GridView:
<asp:GridView ID="GridView1" runat="server" BorderColor="#ececec" BorderWidth="2px" HeaderStyle-BackColor="#F6F6F6" HeaderStyle-Font-Bold="true" RowStyle-BackColor="white" AlternatingRowStyle-BackColor="#F6F6F6" AutoGenerateColumns="False" ShowFooter="true" DataKeyNames="UsuarioId" ShowHeaderWhenEmpty="True" OnRowCommand="GridView1_OnRowCommand" OnRowEditing="GridView1_OnRowEditing" OnRowCancelingEdit="GridView1_OnRowCancelingEdit" OnRowUpdating="GridView1_OnRowUpdating" OnRowDeleting="GridView1_OnRowDeleting" Width="100%" CssClass="GridViewStyle" >
<EmptyDataTemplate>
<div>
No hay datos para mostrar :(
</div>
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="Tipo Usuario ID (Dato momentaneo)">
<ItemTemplate>
<asp:Label Text='<%#Eval("tipo") %>' runat="server">
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtTipoUsuarioId" Text='<%#Eval("tipo") %>' runat="server" ></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:DropDownList ID="dropdown" runat="server" AppendDataBoundItems="True" DataTextField="tipoUsuario" DataValueField="tipoUsuarioId" DataSourceID="sqlDB" CssClass="ddl">
</asp:DropDownList>
<asp:SqlDataSource ID="sqlDB" ConnectionString="<%$ ConnectionStrings:conn%>" runat="server" SelectCommand="Select * from Tipo_Usuario"></asp:SqlDataSource>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Nombre">
<ItemTemplate>
<asp:Label Text='<%#Eval("nombre") %>' runat="server">
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtNombre" Text='<%#Eval("nombre") %>' runat="server" required="true"></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNombreFooter" runat="server"></asp:TextBox>
<br/>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1" ForeColor="Red" runat="server" ValidationGroup="Group1" ControlToValidate="txtNombreFooter"
ErrorMessage="Requiere nombre!"/>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Contraseña">
<ItemTemplate>
<asp:Label Text='<%#Eval("contraseña") %>' runat="server" >
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtContraseña" Text='<%#Eval("contraseña") %>' runat="server" required="true" ></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtContraseñaFooter" runat="server" ></asp:TextBox>
<br/>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator2" ForeColor="Red" runat="server" ValidationGroup="Group1" ControlToValidate="txtContraseñaFooter"
ErrorMessage="Requiere contraseña!"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Habilitado">
<ItemTemplate>
<asp:Label id="habilitado" Text='<%#Eval("habilitado") %>' runat="server">
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtHabilitado" Text='<%#Eval("habilitado") %>' runat="server" ></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton CssClass="btn btn-warning" BackColor="#EC971F" Text="Editar" ForeColor="white" CommandName="Edit" runat="server" ><i class="fa fa-pencil" aria-hidden="true"></i></asp:LinkButton>
<asp:LinkButton CssClass="btn btn-danger" Text="Borrar" CommandName="Delete" runat="server" > <i class="fa fa-trash-o" aria-hidden="true"></i></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ImageUrl="Assets/ICONS/Save.png" CommandName="Update" ToolTip="Update" Width="20" Height="20" runat="server"/>
<asp:ImageButton ImageUrl="Assets/ICONS/Cancel.png" CommandName="Cancel" ToolTip="Cancel" Width="20" Height="20" runat="server"/>
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ImageUrl="Assets/ICONS/xls.png" OnClick="ExportDataToExcel" Width="40" Height="40" runat="server"/>
<asp:LinkButton CssClass="btn btn-success" Text="Agregar" CommandName="Agregar" runat="server" ValidationGroup="Group1"></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is the code to export:
public void ExportDataToExcel(object sender, EventArgs e)
{
GridView1.AllowPaging = false;
GridView1.AllowSorting = false;
GridView1.AutoGenerateEditButton = false;
GridView1.AutoGenerateDeleteButton = false;
Response.ClearContent(); //Clear any content
Response.AppendHeader("content-disposition","attachment; filename=Usuarios.xls"); //Export as XLS (Excel)
Response.ContentType = "application/excel";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter); //Saves all the content including rows.
GridView1.RenderControl(htmlTextWriter);
Response.Write(stringWriter.ToString()); //Gridview data is going to be converted for a xls file
Response.End();
}
This is what I get:
Like I said on the title, I want to hide TextBox and buttons while exporting to excel in order to only see the data. Those controls are inside EditItemTemplate tags. On the aspx website the GridView show data from SQL server database, what I want to do is to export it as a table.

Related

How to add footer row in gridview populated by list in ASP.NET

I need to populate a GridView with list and I want to add a footer row so the user can add a new row.
This is what my front end looks like.
<asp:GridView ID="GridView1" AllowPaging="true" ShowFooter="true" PageSize="5" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowEditing="GridView1_RowEditing"
runat="server" CellPadding="3" GridLines="None" CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt"
OnRowCancelingEdit="GridView1_RowCancelingEdit">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ImageUrl="~/Images/edit.png" runat="server" CommandName="Edit" ToolTip="Edit" Width="20px" Height="20px"/>
<asp:ImageButton ImageUrl="~/Images/delete.png" runat="server" CommandName="Delete" ToolTip="Delete" Width="20px" Height="20px"/>
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ImageUrl="~/Images/save.png" runat="server" CommandName="Update" ToolTip="Update" Width="20px" Height="20px"/>
<asp:ImageButton ImageUrl="~/Images/cancel.png" runat="server" CommandName="Cancel" ToolTip="Cancel" Width="20px" Height="20px"/>
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ImageUrl="~/Images/addnew.png" runat="server" CommandName="AddNew" ToolTip="Add New" Width="20px" Height="20px"/>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This is how I populate the GridView.
protected List<Emp> GetEmpList()
{
List<Emp> lEmp = new List<Emp>();
Emp oemp = new Emp(1234, "Upendra", "Noida");
lEmp.Add(oemp);
oemp = new Emp(1934, "Rahul", "Noida");
lEmp.Add(oemp);
//.......
return lEmp;
}
protected void BindGridList()
{
GridView1.DataSource = GetEmpList();
GridView1.DataBind();
}
Here is a picture of my grid.
My question is how can I add a footer row thank you for your help.
We need to modify the following to achieve Footer controls in GridView.
1) GridView - Change to AutoGenerateColumns="False"
2) Add all the columns to the Grid in the design view with the TemplateField
3) Describe EditItemTemplate, ItemTemplate, FooterTemplate for the columns
4) In the code behind file, access the values using GridView1.FooterRow.FindControl
Sample ASPX Code
<asp:GridView ID="GridView1" AllowPaging="True" ShowFooter="True" PageSize="5" OnPageIndexChanging="GridView1_PageIndexChanging" OnRowEditing="GridView1_RowEditing"
runat="server" CellPadding="3" GridLines="None" CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt"
OnRowCancelingEdit="GridView1_RowCancelingEdit" AutoGenerateColumns="False">
<AlternatingRowStyle CssClass="alt"></AlternatingRowStyle>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ImageUrl="~/Images/edit.png" runat="server" CommandName="Edit" ToolTip="Edit" Width="20px" Height="20px" />
<asp:ImageButton ImageUrl="~/Images/delete.png" runat="server" CommandName="Delete" ToolTip="Delete" Width="20px" Height="20px" />
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ImageUrl="~/Images/save.png" runat="server" CommandName="Update" ToolTip="Update" Width="20px" Height="20px" />
<asp:ImageButton ImageUrl="~/Images/cancel.png" runat="server" CommandName="Cancel" ToolTip="Cancel" Width="20px" Height="20px" />
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ImageUrl="~/Images/addnew.png" runat="server" CommandName="AddNew" ToolTip="Add New" Width="20px" Height="20px" OnClick="btnAddNew_Click" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Id">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Id") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Name") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtNameFooter" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="City">
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("City") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Bind("City") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtCityFooter" runat="server"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Sample Code Behind Code:
protected void btnAddNew_Click(object sender, EventArgs e)
{
TextBox txtName = GridView2.FooterRow.FindControl("txtNameFooter") as TextBox;
TextBox txtCity = GridView2.FooterRow.FindControl("txtCityFooter") as TextBox;
cmd.CommandText = $"INSERT INTO tblLocation(Name,City) VALUES('{txtName.Text}','{txtCity.Text}')";
}

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

Using identifier in gridview

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

GridView Textboxes not getting cleared on web tab change

I have a Page which has a 2 level web tab . The Content tabs FIXED and VARIABLE in turn has a web tab. This web tab is loaded with a User control which has a gridview.
My problem is the textboxes in the Gridview are not cleared on going from one sub tab to next sub tab . I tried all possible methods :
1.Bind grid to null ( datasource and DatasoruceId )
2. grid dispose
3. grid columns clear
No luck !!!.. HELP!!!
Note : I am modifying the data in the textboxes from javascript.
<ig:Webtab id="wi" runat="server" width="938px" displaymode="Scrollable" meta:resourcekey="wtabInvestmentTypeResource1">
<ClientEvents SelectedIndexChanging="webTab_SelectedIndexChanging" />
<AutoPostBackFlags SelectedIndexChanged="On" />
<Tabs>
<ig:ContentTabItem runat="server" Text="Variable Investment Type" meta:resourcekey="ContentTabItemResource1">
<Template>
<div class="clear vspacesmall hspacenarrow">
</div>
<ig:WebTab ID="wv" runat="server" Width="908px" DisplayMode="Scrollable" ClientIDMode="Static"
meta:resourcekey="wtabVariableResource1">
<ClientEvents SelectedIndexChanging="webTab_SelectedIndexChanging" />
<AutoPostBackFlags SelectedIndexChanged="On" />
</ig:WebTab>
</Template>
</ig:ContentTabItem>
<ig:ContentTabItem runat="server" Text="Fixed Investment Type" meta:resourcekey="ContentTabItemResource2">
<Template>
<div class="clear vspacesmall hspacenarrow">
</div>
<ig:WebTab ID="wf" runat="server" Width="908px" DisplayMode="Scrollable" class="tabs"
meta:resourcekey="wtabFixedResource1">
<ClientEvents SelectedIndexChanging="webTab_SelectedIndexChanging" />
<AutoPostBackFlags SelectedIndexChanged="On" />
</ig:WebTab>
The web tab loads a user control which has the following gridview :
<div class="clear vspacesmall gridtablearea scrollPanel-horizontal Contol-Max-Height">
<asp:UpdatePanel ID="upBuyMultipleGetDiscount" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gvInvestmentDetails" runat="server" OnRowDataBound="gvInvestmentDetails_RowDataBound"
TabIndex="5" AutoGenerateColumns="False" CssClass="gridtable scrollPanel-horizontal" Width="100%" meta:resourcekey="gvInvestmentDetails_DefaultResource1"
EnableViewState="true" ViewStateMode="Enabled" ShowFooter="true" OnRowCommand="gvInvestmentDetails_Row_Command">
<Columns>
<asp:BoundField DataField="InvestmentTypeId" />
<asp:BoundField DataField="CustomerCombinationId" />
<asp:BoundField DataField="ProductId" />
<asp:TemplateField HeaderText="Account" ItemStyle-Width="100px" meta:resourcekey="Account">
<ItemTemplate>
<asp:Label ID="lblAccountName" runat="server" Text='<%# Eval("CustomerCombinationName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Products" ItemStyle-Width="200px" meta:resourcekey="Products">
<ItemTemplate>
<asp:Label ID="lblProductName" runat="server" Text='<%# Eval("ProductName") %>'></asp:Label>
</ItemTemplate>
<FooterTemplate>
<asp:Label ID="lblTotal" CssClass="fRight boldText" ForeColor="#656565" runat="server" Text='TOTAL :' meta:resourcekey="lblTotal"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Phase Investment Amount" meta:resourcekey="PhaseInvestmentAmount" >
<ItemTemplate>
<asp:Repeater ID="rptrPhases" runat="server" ClientIDMode="Static" OnDataBinding="rptrPhases_OnDataBinding">
<ItemTemplate>
<div style="float: left; padding: 4px;">
<table id="PhaseDetails">
<tr>
<td>
<tr>
<asp:Label ID="lblPhaseID" runat="server" Text='<%# Eval("PhaseID") %>' Visible="False"></asp:Label>
<asp:Label ID="lblPhaseName" Class="vspacesmall" runat="server" Text='<%# Eval("PhaseName") %>' ></asp:Label><br />
<asp:TextBox ID="txtPhaseAmount" runat="server" Text='<%# Eval("PhaseAmount", "{0:F2}") %>' CssClass="tar"
ClientIDMode="Static" Width="80px" MaxLength="27" onpaste="return false;" ViewStateMode="Enabled"
meta:resourcekey="txtPhaseAmount"></asp:TextBox>
</tr>
<tr>
<asp:Label ID="lblUsageAmount" runat="server" Visible="false" Text='<%# Eval("PhaseUpdateAmount", "{0:F2}") %>'></asp:Label>
</tr>
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
<FooterTemplate>
<asp:Repeater ID="rptTotalAmount" runat="server" ClientIDMode="Static">
<ItemTemplate>
<div style="float: left; padding: 4px;">
<table>
<tr>
<td>
<asp:TextBox ID="txtPhaseTotal" Text='<%# Eval("PhaseAmount", "{0:F2}") %>' Width="80px" CssClass="tar boldText"
ForeColor="#656565" runat="server" ViewStateMode="Enabled" ClientIdMode="Static" autocomplete="off" ></asp:TextBox>
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:Repeater>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Roles" ItemStyle-Width="150px" meta:resourcekey="Roles">
<ItemTemplate>
<asp:CheckBoxList ID="chckRoleList" runat="server" DataTextField="RoleName"
DataValueField="RoleId" EnableViewState="true" ViewStateMode="Enabled" onclick="checkBoxLstChanged(this.id,'chkSelectAll');SetIsChanged('1');">
</asp:CheckBoxList>
<asp:RadioButtonList ID="rdbRoleList" runat="server" DataTextField="RoleName"
DataValueField="RoleId" EnableViewState="true" ViewStateMode="Enabled">
</asp:RadioButtonList>
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="chckSelectAll" runat="server" Text="Select All" onclick="setAllCheckBoxes('chckRoleList',this);SetIsChanged('1');" meta:resourcekey="chckSelectAll">
</asp:CheckBox>
<br>
<asp:Button ID="btnRemove" runat="server" CssClass="btnStyle fLeft" Text="Remove" OnClientClick="return ValidateRemoveRoles('gvInvestmentDetails')"
CommandName="RemoveRoles" CommandArgument='<%# Container.DataItemIndex %>'
meta:resourcekey="btnRemove" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="InvestmentAmount" meta:resourcekey="InvestmentAmount">
<ItemTemplate>
<asp:TextBox ID="txtInvAmt" Width="80px" runat="server" Text='<%# Eval("InvestmentAmount","{0:F2}") %>'
ClientIdMode="Static" ViewStateMode="Enabled" CssClass="fRight tar boldText" ></asp:TextBox >
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtTotalInvestment" ClientIdMode="Static" Width="80px" ViewStateMode="Enabled" CssClass="fRight tar boldText " ForeColor="#656565" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField DataField="RecordStatus" />
</Columns>
<%-- <FooterStyle HorizontalAlign="Left" CssClass="boldText" ForeColor="#656565" />--%>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
</div>
The back end code for loading the USer control :
private void LoadInvestmentDetails(int investmentTypeId, WebTab currentWebTab, int tabIndex)
{
Panel panel = GetPanelToBeLoaded(investmentTypeId);
if (currentWebTab.Tabs[tabIndex].Controls.Count == 0)
{
currentWebTab.Tabs[tabIndex].Controls.Add(panel);
budgetDetailsControl.Initialize(investmentTypeId);
budgetDetailsControl.InvestmentDetailsSaved += new ProjectInvestmentDetailsSavedEventHandler(BudgetDetailsControl_BudgetDetailsSaved);
PreviouslyLoadedTab = int.Parse(currentWebTab.Tabs[currentWebTab.SelectedIndex].UserControlUrl);
}
// other code
}
private Panel GetPanelToBeLoaded(int investmentTypeId)
{
System.Web.UI.Control userControl = GetInvestmentDetailsUserControlUrl();
Panel panel = new Panel();
panel.Controls.Add(userControl);
budgetDetailsControl = (IProjectInvestmentDetailsControl)userControl;
budgetDetailsControl.InvestmentTypeID = investmentTypeId;
return panel;
}
private System.Web.UI.Control GetInvestmentDetailsUserControlUrl()
{
return LoadControl(ProjectCommonKeys.URL_PROJECT_BUDGET_DETAILS);
}
The Usercontrol implments the IprojectInvestmentDetails interface and the initalize function of the UC is called first for the binding etc
I figured out the problem. Each user control bound to the sub tab shud be given a unique Id..or else even if we bind new data the data from the earlier instance will persist.
.
private Panel GetPanelToBeLoaded(int investmentTypeId)
{
System.Web.UI.Control userControl = GetInvestmentDetailsUserControlUrl();
**userControl.ID = investmentTypeId.ToString();**
Panel panel = new Panel();
panel.Controls.Add(userControl);
projectInvestmentDetailsControl = (IProjectInvestmentDetailsControl)userControl;
projectInvestmentDetailsControl.InvestmentTypeID = investmentTypeId;
projectInvestmentDetailsControl.UserContext = userContext;
projectInvestmentDetailsControl.PlanningWizardDataManager = PlanningWizardDataManager;
projectInvestmentDetailsControl.PlanningServiceWrapper = PlanningServiceWrapper;
return panel;
}`
Thanks fr the help...

Categories

Resources