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";
}
}
Related
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.
1. my .aspx code is
asp:GridView ID="gvaccmaster" DataKeyNames="id"
runat="server" AutoGenerateColumns="False"
HeaderStyle-Font-Bold="true"
OnRowCancelingEdit="gridView_RowCancelingEdit"
OnRowDeleting="gridView_RowDeleting"
OnRowEditing="gridView_RowEditing"
OnRowUpdating="gridView_RowUpdating"
OnRowDataBound="gridView_RowDataBound" Font-Names="Arial"
Font-Strikeout="False" Font-Underline="False"
OnPageIndexChanging="OnPageIndexChanging" CellPadding="2"
Style="text-align: center; vertical-align: middle"
BorderColor="Black" BorderWidth="2px"> <AlternatingRowStyle
BorderStyle="None" /> <Columns> <asp:TemplateField HeaderText="ID"
ConvertEmptyStringToNull="False"> <ItemTemplate> <asp:Label ID="ID"
runat="server" Text='<%#Eval("id") %>' /> </ItemTemplate>
<EditItemTemplate> <asp:Label ID="id" runat="server"
Text='<%#Eval("id") %>' /> </EditItemTemplate> </asp:TemplateField>
<asp:TemplateField HeaderText="Name"
ConvertEmptyStringToNull="False"> <ItemTemplate> <asp:Label
ID="name" runat="server" Text='<%#Eval("name") %>' />
</ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtname"
runat="server" Text='<%#Eval("name") %>' />
<asp:RequiredFieldValidator runat="server" ID="rfv0"
ControlToValidate="txtname" ErrorMessage="*" ForeColor="Red"
ValidationGroup="validaiton" /> </EditItemTemplate>
</asp:TemplateField> <asp:TemplateField HeaderText="Opening
Balance"> <ItemTemplate> <asp:Label ID="opbalance" runat="server"
Text='<%#Eval("openingbalance") %>' /> </ItemTemplate>
<EditItemTemplate> <asp:TextBox ID="txtopbalance" runat="server"
Text='<%#Eval("openingbalance") %>' /> <asp:RequiredFieldValidator
runat="server" ID="rfv1" ControlToValidate="txtopbalance"
ErrorMessage="*" ForeColor="Red" ValidationGroup="validaiton" />
<asp:RegularExpressionValidator ID="rev4" runat="server"
ErrorMessage="invalid opening balance" ValidationGroup="validaiton"
ControlToValidate="txtopbalance" ForeColor="Red"
ValidationExpression="^\d+$"> </asp:RegularExpressionValidator>
</EditItemTemplate> </asp:TemplateField> <asp:TemplateField
HeaderText="Contact Person"> <ItemTemplate> <asp:Label ID="cperson"
runat="server" Text='<%#Eval("contactperson") %>' /> </ItemTemplate>
<EditItemTemplate> <asp:TextBox ID="txtcperson" runat="server"
Text='<%#Eval("contactperson") %>' /> <asp:RequiredFieldValidator
runat="server" ID="rfv2" ControlToValidate="txtcperson"
ErrorMessage="*" ForeColor="Red" ValidationGroup="validaiton" />
</EditItemTemplate> </asp:TemplateField> <asp:TemplateField
HeaderText="Address"> <ItemTemplate> <asp:Label ID="address"
runat="server" Text='<%#Eval("address") %>' /> </ItemTemplate>
<EditItemTemplate> <asp:TextBox ID="txtaddress" runat="server"
Text='<%#Eval("address") %>' /> <asp:RequiredFieldValidator
runat="server" ID="rfv3" ControlToValidate="txtaddress"
ErrorMessage="*" ForeColor="Red" ValidationGroup="validaiton" />
</EditItemTemplate> </asp:TemplateField> <asp:TemplateField
HeaderText="City"> <ItemTemplate> <asp:Label ID="city"
runat="server" Text='<%#Eval("city") %>' /> </ItemTemplate>enter
code here <EditItemTemplate> <asp:DropDownList ID="ddlcity"
runat="server" Height="25px" Width="100px">
<asp:ListItem>Ahmedabad</asp:ListItem>
<asp:ListItem>Baroda</asp:ListItem>
<asp:ListItem>Rajkot</asp:ListItem>
<asp:ListItem>Udaipur</asp:ListItem>
<asp:ListItem>Jaipur</asp:ListItem>
<asp:ListItem>Ajmer</asp:ListItem>
<asp:ListItem>Jodhpur</asp:ListItem>
<asp:ListItem>Bhopal</asp:ListItem>
<asp:ListItem>Indore</asp:ListItem>
<asp:ListItem>Gwalior</asp:ListItem>
<asp:ListItem>Ujjain</asp:ListItem>
<asp:ListItem>Mumbai</asp:ListItem>
<asp:ListItem>Pune</asp:ListItem>
<asp:ListItem>Nagpur</asp:ListItem>
<asp:ListItem>Nasik</asp:ListItem>
<asp:ListItem>Aurangabad</asp:ListItem>
<asp:ListItem>Akola</asp:ListItem> </asp:DropDownList>
</EditItemTemplate> </asp:TemplateField> <asp:TemplateField
HeaderText="State"> <ItemTemplate> <asp:Label ID="state"
runat="server" Text='<%#Eval("state") %>' /> </ItemTemplate>
<EditItemTemplate> <asp:DropDownList ID="ddlstate" runat="server"
Height="25px" Width="150px"> <asp:ListItem>Gujarat</asp:ListItem>
<asp:ListItem>Rajasthan</asp:ListItem> <asp:ListItem>Madhya
Pradesh</asp:ListItem> <asp:ListItem>Maharashtra</asp:ListItem>
</asp:DropDownList> </EditItemTemplate> </asp:TemplateField>
<asp:TemplateField HeaderText="Area"> <ItemTemplate> <asp:Label
ID="area" runat="server" Text='<%#Eval("area") %>' />
</ItemTemplate> <EditItemTemplate> <asp:TextBox ID="txtarea"
runat="server" Text='<%#Eval("area") %>' />
<asp:RequiredFieldValidator runat="server" ID="rfv4"
ControlToValidate="txtarea" ErrorMessage="*" ForeColor="Red"
ValidationGroup="validaiton" /> </EditItemTemplate>
</asp:TemplateField> <asp:TemplateField HeaderText="Pin Code">
<ItemTemplate> <asp:Label ID="pincode" runat="server"
Text='<%#Eval("pincode") %>' /> </ItemTemplate> <EditItemTemplate>
<asp:TextBox ID="txtpincode" runat="server" Text='<%#Eval("pincode")
%>' /> <asp:RequiredFieldValidator runat="server" ID="rfv5"
ControlToValidate="txtpincode" ErrorMessage="*" ForeColor="Red"
ValidationGroup="validaiton" /> <asp:RegularExpressionValidator
ID="rev3" runat="server" ErrorMessage="invalid pincode"
ValidationGroup="validaiton" ControlToValidate="txtpincode"
ForeColor="Red" ValidationExpression="\d{6}">
</asp:RegularExpressionValidator> </EditItemTemplate>
</asp:TemplateField> <asp:TemplateField HeaderText="Mobile">
<ItemTemplate> <asp:Label ID="mobile" runat="server"
Text='<%#Eval("mobile") %>' /> </ItemTemplate> <EditItemTemplate>
<asp:TextBox ID="txtmobile" runat="server" Text='<%#Eval("mobile")
%>' /> <asp:RequiredFieldValidator runat="server" ID="rfv6"
ControlToValidate="txtmobile" ErrorMessage="*" ForeColor="Red"
ValidationGroup="validaiton" /> <asp:RegularExpressionValidator
ID="rev2" runat="server" ErrorMessage="invalid mobile"
ValidationGroup="validaiton" ControlToValidate="txtmobile"
ForeColor="Red" ValidationExpression="^[7-9][0-9]{9}$">
</asp:RegularExpressionValidator> </EditItemTemplate>
</asp:TemplateField> <asp:TemplateField HeaderText="E-Mail">
<ItemTemplate> <asp:Label ID="email" runat="server"
Text='<%#Eval("email") %>' /> </ItemTemplate> <EditItemTemplate>
<asp:TextBox ID="txtemail" runat="server" Text='<%#Eval("email") %>'
/> <asp:RequiredFieldValidator runat="server" ID="rfv7"
ControlToValidate="txtemail" ErrorMessage="*" ForeColor="Red"
ValidationGroup="validaiton" /> <asp:RegularExpressionValidator
ID="rev1" runat="server" ErrorMessage="invalid email"
ValidationGroup="validaiton" ControlToValidate="txtemail"
ForeColor="Red"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator> </EditItemTemplate>
</asp:TemplateField> <asp:TemplateField HeaderText="Actions">
<ItemTemplate> <asp:Button ID="ButtonEdit" runat="server"
CommandName="Edit" Text="Edit" Width="50px" /> <asp:Button
ID="ButtonDelete" runat="server" CommandName="Delete" Text="Delete"
Width="50px" /> </ItemTemplate> <EditItemTemplate> <asp:Button
ID="ButtonUpdate" runat="server" CommandName="Update" Text="Update"
ValidationGroup="validaiton" Width="60px" /> <asp:Button
ID="ButtonCancel" runat="server" CommandName="Cancel" Text="Cancel"
Width="60px" /> </EditItemTemplate> </asp:TemplateField> </Columns>
<EditRowStyle BorderStyle="Solid" BorderWidth="2px" /> <HeaderStyle
BorderColor="Black" BorderStyle="Solid" BorderWidth="2px"
Font-Names="Cambria" Font-Size="Large" BackColor="#CCCCCC"
Font-Bold="False" ForeColor="Blue" HorizontalAlign="Center"
VerticalAlign="Middle"></HeaderStyle> <RowStyle
HorizontalAlign="Center" VerticalAlign="Middle" /> </asp:GridView>
and code behind the page is
protected void btnview_Click(object sender, EventArgs e)
{
string query = txtsearch.Text;
foreach(GridViewRow row in gvaccmaster.Rows)
{
row.Visible = false;
}
if(query.Trim() != "")
{
foreach (GridViewRow row in gvaccmaster.Rows)
{
foreach (TableCell cell in row.Cells)
{
string cellText = cell.Text;
if (cell.Text == "" && cell.Controls.Count > 0)
{
cellText = ((LiteralControl)cell.Controls[0]).Text;
}
if (cellText.IndexOf(query) > -1)
{
row.Visible = true; break;
}
}
}
}
else
{
foreach (GridViewRow row in gvaccmaster.Rows)
{
row.Visible = true;
}
}
}
// im getting error on line
//if (cell.Text == "" && cell.Controls.Count > 0)
//{
// cellText = ((DataBoundLiteralControl)cell.Controls[0]).Text;
//}
I'm creating a page to enter employee's leave details in a dynamic gridview. Entry of data will be done by the from the footer of the gridview. When I try to get the values from the footer, all the text values as well as other values are coming as null or "".
Here is the code of RowCommand:
protected void gvEmployeeDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("ADD"))
{
TextBox txtAddEmpID = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddEmpID");
RadioButtonList rblFooter = (RadioButtonList)gvEmployeeDetails.FooterRow.FindControl("rblFooter");
TextBox txtAddDoj = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddDoj");
TextBox txtAddLeaves = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddLeaves");
TextBox txtAddDesignation = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddDesignation");
conn.Open();
string cmdstr = "insert into tblLeaves(EmpId,IsActive,DOJ,Leaves,Designation) values(#EmpId,#IsActive,#DOJ,#Leaves,#Designation)";
SqlCommand cmd = new SqlCommand(cmdstr, conn);
cmd.Parameters.AddWithValue("#EmpId", txtAddEmpID.Text);
cmd.Parameters.AddWithValue("#IsActive", rblFooter.SelectedValue);
cmd.Parameters.AddWithValue("#DOJ", txtAddDoj.Text);
cmd.Parameters.AddWithValue("#Leaves", txtAddLeaves.Text);
cmd.Parameters.AddWithValue("#Designation", txtAddDesignation.Text);
cmd.ExecuteNonQuery();
conn.Close();
BindData();
}
}
And below is the gridview:
<asp:GridView ID="gvEmployeeDetails" runat="server" Width="100%"
AutoGenerateColumns="False" ShowFooter="True"
onrowcommand="gvEmployeeDetails_RowCommand"
onrowdeleting="gvEmployeeDetails_RowDeleting"
onrowupdating="gvEmployeeDetails_RowUpdating"
onrowcancelingedit="gvEmployeeDetails_RowCancelingEdit"
onrowediting="gvEmployeeDetails_RowEditing" style="text-align: center" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3">
<Columns>
<asp:TemplateField HeaderText="Employee ID">
<FooterTemplate>
<asp:TextBox ID="txtAddEmpID" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvFooterEmpID" runat="server" ControlToValidate="txtAddEmpID" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblEmpID" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "EmpId") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditEmpID" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "EmpId") %>'></asp:Label>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Active">
<EditItemTemplate>
<asp:RadioButtonList ID="rblEdit" runat="server">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:RadioButtonList>
</EditItemTemplate>
<FooterTemplate>
<asp:RadioButtonList ID="rblFooter" runat="server">
<asp:ListItem>Yes</asp:ListItem>
<asp:ListItem>No</asp:ListItem>
</asp:RadioButtonList>
<asp:RequiredFieldValidator ID="rfvFooterIsActive" runat="server" ControlToValidate="rblFooter" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</FooterTemplate>
<ItemTemplate>
<asp:Label ID="lblIsActive" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "IsActive") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date Of Joining">
<ItemTemplate>
<asp:Label ID="lblDoj" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "DOJ") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDoj" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "DOJ") %>'></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="txtDoj_CalendarExtender" runat="server" BehaviorID="txtDoj_CalendarExtender" TargetControlID="txtDoj" />
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddDoj" runat="server" MaxLength="10" OnTextChanged="txtAddDoj_TextChanged" ></asp:TextBox>
<ajaxToolkit:CalendarExtender ID="txtAddDoj_CalendarExtender" runat="server" BehaviorID="txtAddDoj_CalendarExtender" TargetControlID="txtAddDoj" />
<asp:RequiredFieldValidator ID="rfvFooterDOJ" runat="server" ControlToValidate="txtAddDoj" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="No. Of Leaves">
<ItemTemplate>
<asp:Label ID="lblLeaves" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Leaves") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtLeaves" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Leaves") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddLeaves" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvFooterLeaves" runat="server" ControlToValidate="txtAddLeaves" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Designation">
<ItemTemplate>
<asp:Label ID="lblDesignation" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Designation") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDesignation" runat="server" Text='<%#DataBinder.Eval(Container.DataItem, "Designation") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtAddDesignation" runat="server" ></asp:TextBox>
<asp:RequiredFieldValidator ID="rfvFooterDesig" runat="server" ControlToValidate="txtAddDesignation" ErrorMessage="*" ForeColor="Red"></asp:RequiredFieldValidator>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:ImageButton ID="imgbtnEdit" runat="server" CommandName="Edit" ImageUrl="~/Images/Edit.png" Height="32px" Width="32px"/>
<asp:ImageButton ID="imgbtnDelete" runat="server" CommandName="Delete" ImageUrl="~/Images/Delete.png" Height="32px" Width="32px"/>
</ItemTemplate>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" runat="server" CommandName="Update" ImageUrl="~/Images/icon-update.png"/>
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Images/icon-Cancel.png"/>
</EditItemTemplate>
<FooterTemplate>
<asp:LinkButton ID="lbtnAdd" runat="server" CommandName="ADD" Text="Add" Width="100px"></asp:LinkButton>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
Please correct me where I'm going wrong.
You are not using sender in your find control code line. Try to replace below line.
TextBox txtAddEmpID = (TextBox)gvEmployeeDetails.FooterRow.FindControl("txtAddEmpID");
this.
protected void gridview_RowCommand(object sender, System.Web.UI.WebControls.GridViewCommandEventArgs e)
{
if (e.CommandName == "Add") {
TextBox txtAddEmpID = (TextBox)((GridView)sender).FooterRow.FindControl("txtAddEmpID");
}
}
<asp:Panel ID="pnlGrdShift" runat="server" ScrollBars="Auto" Width="900px" Height="520px" CssClass="srcColor">
<cc1:GridView ID="gvShift" runat="server" AutoGenerateColumns="False" AllowSorting="True"
CssClass="grid"
OnDataBound="gvShift_DataBound"
DataSourceID="odsShiftDetails"
AllowPaging="True"
ShowFooter="false"
onrowcancelingedit="gvShift_RowCancelingEdit"
onrowcommand="gvShift_RowCommand"
onrowdeleting="gvShift_RowDeleting"
onrowediting="gvShift_RowEditing"
onrowupdating="gvShift_RowUpdating"
OnSelectedIndexChanged="gvShift_SelectedIndexChanged"
OnRowDataBound="gvShift_RowDataBound">
<AlternatingRowStyle CssClass="altrowstyle" />
<HeaderStyle CssClass="headerstyle" />
<RowStyle CssClass="rowstyle" Wrap="false" />
<EmptyDataRowStyle BackColor="#edf5ff" Height="300px" VerticalAlign="Middle" HorizontalAlign="Center" />
<EmptyDataTemplate >
No Records Found
</EmptyDataTemplate>
<Columns>
<asp:TemplateField HeaderText="E Code" SortExpression="userecode" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblUserECode" runat="server" Text='<%#Eval("userecode") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditUserECode" runat="server" Text='<%#Eval("userecode") %>' style="width:50px;" CssClass="GridContent" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="User Name" SortExpression="username" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblUserName" runat="server" Text='<%#Eval("username") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblEditUserName" runat="server" Text='<%#Eval("username") %>' style="width:100px;" CssClass="GridContent"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shift Start Time" SortExpression="ShiftStartTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblShiftStartTime" runat="server" Text='<%#Eval("ShiftStartTime") %>' CssClass="GridContent"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlShiftStartTime" runat="server" Text='<%#Eval("ShiftStartTime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlShiftStartTime" runat="server" ControlToValidate="ddlShiftStartTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Shift End Time" SortExpression="ShiftEndTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblShiftEndTime" runat="server" Text='<%#Eval("ShiftEndTime") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlShiftEndTime" runat="server" Text='<%#Eval("ShiftEndTime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlShiftEndTime" runat="server" ControlToValidate="ddlShiftEndTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<%--<asp:BoundField DataField="ShiftEndTIme" HeaderText="Shift End Time" SortExpression="ShiftEndTIme"/>--%>
<asp:TemplateField HeaderText="Saturday Shift Start Time" SortExpression="WeekendShiftStartTime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblWeekendShiftStartTime" runat="server" Text='<%#Eval("WeekendShiftStartTime") %>' CssClass="GridContent" />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlWeekendShiftStartTime" runat="server" Text='<%#Eval("WeekendShiftStartTime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlWeekendShiftStartTime" runat="server" ControlToValidate="ddlWeekendShiftStartTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Saturday Shift End Time" SortExpression="weekendshiftendtime" HeaderStyle-Font-Bold="true" HeaderStyle-Font-Names="Calibre" HeaderStyle-ForeColor="White">
<ItemTemplate>
<asp:Label ID="lblWeekendShiftEndTime" runat="server" Text='<%#Eval("weekendshiftendtime") %>' CssClass="GridContent"/>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="ddlWeekendShiftEndTime" runat="server" Text='<%#Eval("weekendshiftendtime") %>' style="width:65px;" CssClass="GridContent" />
<asp:RegularExpressionValidator ID="RegularExpValidatorddlWeekendShiftEndTime" runat="server" ControlToValidate="ddlWeekendShiftEndTime" ValidationExpression="^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$" ErrorMessage="*" Font-Bold="true" ForeColor="Red" ToolTip="Must be in HH:MM" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False" >
<EditItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update" Text="Update" ForeColor="White"></asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel" Text="Cancel" ForeColor="White"></asp:LinkButton>
</EditItemTemplate>
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="False" CommandName="Edit" Text="Edit" ForeColor="White"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<PagerTemplate >
<table width="100%" >
<tr>
<td style="text-align: left">
Page Size:
<asp:DropDownList ID="ddPageSize" runat="server" EnableViewState="true" OnSelectedIndexChanged="ddPageSize_SelectedIndexChanged" AutoPostBack="true" style="width:50px;">
<asp:ListItem Text="10" ></asp:ListItem>
<asp:ListItem Text="20" ></asp:ListItem>
<asp:ListItem Text="30" ></asp:ListItem>
<asp:ListItem Text="40" ></asp:ListItem>
<asp:ListItem Text="50" ></asp:ListItem>
</asp:DropDownList>
</td>
<td style="text-align: right">
<asp:Label ID="lblPageCount" runat="server"></asp:Label>
</td>
</tr>
</table>
</PagerTemplate>
</cc1:GridView>
</asp:Panel></td></tr>
</table>
<div style="margin-top:5px" class="PagerGrid">
<asp:DataPager ID="pager" runat="server" PagedControlID="gvShift">
<Fields>
<asp:NextPreviousPagerField FirstPageText="<<" LastPageText=">>"
NextPageText=">" PreviousPageText="<" ShowFirstPageButton="True"
ShowNextPageButton="False" ButtonCssClass="datapager" />
<asp:NumericPagerField ButtonCount="10" NumericButtonCssClass="datapager" CurrentPageLabelCssClass="datapager" />
<asp:NextPreviousPagerField LastPageText=">>" NextPageText=">"
ShowLastPageButton="True" ShowPreviousPageButton="False" ButtonCssClass="datapager" />
</Fields>
</asp:DataPager>
</div>
<br />
<asp:ObjectDataSource ID="odsShiftDetails" runat="server"
SelectMethod="GetShiftInfoSortedPage" TypeName="EQ.DAL.ShiftInfoDB"
EnablePaging="True" SelectCountMethod="GetShiftInfoCount"
SortParameterName="sortExpression">
<SelectParameters>
<asp:ControlParameter ControlID="hfSearchCriteria" Name="searchCriteria" Direction="Input" />
</SelectParameters>
</asp:ObjectDataSource>
Code behind for Row Updation is:-
protected void gvShift_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
try
{
TextBox txtShiftStartTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlShiftStartTime");
TextBox txtShiftEndTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlShiftEndTime");
TextBox txtWeekendShiftStartTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlWeekendShiftStartTime");
TextBox txtWeekendShiftEndTime = (TextBox)gvShift.Rows[e.RowIndex].FindControl("ddlWeekendShiftEndTime");
Label lblUserecode = (Label)gvShift.Rows[e.RowIndex].FindControl("lblEditUserECode");
string userecode = lblUserecode.Text.ToString();
string _ShiftStart = txtShiftStartTime.Text.ToString();
string _ShiftEnd = txtShiftEndTime.Text.ToString();
string _WeekendShiftStart = txtWeekendShiftStartTime.Text.ToString();
string _WeekendShiftend = txtWeekendShiftEndTime.Text.ToString();
EmployeeQuotientCL.Entities.ConfigurationVariables _configVariables = new ConfigurationVariables();
string databaseConnectionString = _configVariables.ConnectionString;
SqlConnection sqlConnection = null;
if (((databaseConnectionString + string.Empty) != string.Empty))
{
DBConnect dbConnect = new DBConnect(_configVariables.ConnectionString);
sqlConnection = dbConnect.SQLConnection;
SqlCommand cmd = new SqlCommand();
cmd.Connection = sqlConnection;
cmd.CommandText = "UPDATE UserInfo SET ShiftStartTime ='" + _ShiftStart + "',ShiftEndTime='" + _ShiftEnd.ToString() + "',Weekendshiftstarttime='" + _WeekendShiftStart.ToString() + "',Weekendshiftendtime='" + _WeekendShiftend.ToString() + "' WHERE UserECode=" + userecode.ToString();
sqlConnection.Open();
cmd.ExecuteNonQuery();
gvShift.DataSource = null;
gvShift.DataBind();
sqlConnection.Close();
}
}
catch (Exception ex)
{
}
}
While Updating the Rows in grid , I am getting the below error message.
Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerServerErrorException: >Updating is not supported by ObjectDataSource 'odsShiftDetails' unless the UpdateMethod is >specified.
Guide me how to fix this error. Thanks in advance.
You need to add an update method to your gridview. Look at this tutorial: Gridview ObjectdataSource
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();
}
}