GridView to Excel export with ClosedXML no column names - asp.net

I am generating a gridview with the following code;
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataSourceID="SqlDataSource1" CssClass="gridview" >
<HeaderStyle CssClass="fixedHeader " Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="FirstName" HeaderText="First Name" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" SortExpression="LastName" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="Email" />
<asp:BoundField DataField="Affiliation" HeaderText="Affiliation" SortExpression="Affiliation" />
<asp:BoundField DataField="MailingAddress" HeaderText="Mailing Address" SortExpression="MailingAddress" />
<asp:BoundField DataField="MembershipCategory" HeaderText="Membership Category" SortExpression="MembershipCategory" />
<asp:BoundField DataField="MemberApproved" HeaderText="Membership Approval" SortExpression="MemberApproved" />
</Columns>
</asp:GridView>
Then I am using ClosedXML to export the gridview to excel with a button click:
protected void ExportExcel(object sender, EventArgs e)
{
DataTable dt = new DataTable("GridView_Data");
foreach (TableCell cell in GridView1.HeaderRow.Cells)
{
dt.Columns.Add(cell.Text);
}
foreach (GridViewRow row in GridView1.Rows)
{
dt.Rows.Add();
for (int i = 0; i < row.Cells.Count; i++)
{
dt.Rows[dt.Rows.Count - 1][i] = row.Cells[i].Text;
//dt.Rows[dt.Rows.Count - 1][i] = ((row.Cells[i].Controls[0]) as DataBoundLiteralControl).Text.Trim();
}
}
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dt);
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename= Group_Members_" + DateTime.Now + ".xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
The problem i am running to is that the generated excel file column names are Column1, Column2 etc and not the column names as in the grid. Any idea why and how to fix this please?
AM

solved :
for (int i = 0; i < GridView1.Columns.Count; i++)
{
dt.Columns.Add(GridView1.Columns[i].HeaderText);
}

Related

Could not find a part of the path 'C:\Program Files\IIS Express\saveimg\newimg.jpg'

I am trying to export gridview data with image to pdf. I have used relative path while saving the image to project directory,but i have to manually include every pic into project.I get the above error during html parsing.I am a newbie and trying to learn on my own.Kindly show some light into where i went wrong.My code is given below:
namespace BudgetApp
{
public partial class display : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
/*protected string GetUrl(string page)
{
string[] splits = Request.Url.AbsoluteUri.Split('/');
if (splits.Length >= 2)
{
string url = splits[0] + "//";
for (int i = 2; i < splits.Length - 1; i++)
{
url += splits[i];
url += "/";
}
return url + page;
}
return page;
}*/
public override void VerifyRenderingInServerForm(Control control)
{
//
}
protected void btnPdf_Click(object sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition",
"attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
}
}
My aspx page:
<body>
<h1 style="text-align:center">Monthly Budget Analysis</h1>
<br /><br />
<div id="wrap">
<div class="well">
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" >
<asp:ListItem>January</asp:ListItem>
<asp:ListItem>February</asp:ListItem>
<asp:ListItem>March</asp:ListItem>
<asp:ListItem>April</asp:ListItem>
<asp:ListItem>May</asp:ListItem>
<asp:ListItem>June</asp:ListItem>
<asp:ListItem>July</asp:ListItem>
<asp:ListItem>August</asp:ListItem>
<asp:ListItem>September</asp:ListItem>
<asp:ListItem>October</asp:ListItem>
<asp:ListItem>November</asp:ListItem>
<asp:ListItem>December</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" Height="267px" Width="913px" ShowHeaderWhenEmpty="True" UseAccessibleHeader="False" EmptyDataText="Oops!!No record found">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="month" HeaderText="Month" SortExpression="month" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="expense" HeaderText="Expense" SortExpression="expense" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="budget" HeaderText="Budget" SortExpression="budget" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:BoundField DataField="balance" HeaderText="Balance" SortExpression="balance" >
<ItemStyle HorizontalAlign="Center" />
</asp:BoundField>
<asp:TemplateField HeaderText="Bill" SortExpression="bill">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("bill") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Image ID="Image1" runat="server" Height="100px" ImageUrl='<%# Eval("bill")%>' />
</ItemTemplate>
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#7C6F57" />
<FooterStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#1C5E55" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#666666" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#E3EAEB" />
<SelectedRowStyle BackColor="#C5BBAF" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F8FAFA" />
<SortedAscendingHeaderStyle BackColor="#246B61" />
<SortedDescendingCellStyle BackColor="#D4DFE1" />
<SortedDescendingHeaderStyle BackColor="#15524A" />
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:BudgetConnectionString8 %>" SelectCommand="SELECT * FROM [details] WHERE ([month] = #month)">
<SelectParameters>
<asp:ControlParameter ControlID="DropDownList1" Name="month" PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<asp:Button ID="btnPdf" runat="server" Text="Export to Pdf" OnClick="btnPdf_Click" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</div>
</div>
</body>
Code to save data into database:
namespace BudgetApp
{
public partial class _new : System.Web.UI.Page
{
static String imagelink;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("display.aspx");
}
protected void submit_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this.Page,this.Page.GetType(), "script", "<script type='text/javascript'>Budget();</script>", false);
SqlConnection conn = new SqlConnection(#"Data Source=co\sqlexpress;Initial Catalog=Budget;Integrated Security=true");
conn.Open();
if (file1.HasFile == true)
{
String contenttype = file1.PostedFile.ContentType;
if (contenttype == "image/jpeg")
{
string f=Path.GetFileName(file1.PostedFile.FileName);
file1.SaveAs(HttpContext.Current.Server.MapPath(#"~/saveimg/"+ f));
imagelink = "~/saveimg/" + file1.FileName;
}
}
int a = Convert.ToInt32(exp.Text);
int b = Convert.ToInt32(budget.Text);
int balance = b - a;
SqlCommand obj = new SqlCommand("insert into details values('" + ddlmonth.SelectedValue + "','" + exp.Text + "','" + budget.Text + "','" + balance + "','" + imagelink + "')", conn);
obj.ExecuteNonQuery();
conn.Close();
}
}
}
UPDATE:
I added a new button to give print functionality using javascript,and when the print page popped up ,i selected save as pdf and the image is also getting rendered :)
But i wish i could directly save it to pdf on a button click.My code for printing below:
<script type="text/javascript">
function PrintGridData() {
var prtGrid = document.getElementById('<%=GridView1.ClientID %>');
var prtwin = window.open('', 'PrintGridView',
'left=100,top=100,width=400,height=400,tollbar=0,scrollbars=1,status=0,resizable=1');
prtwin.document.write(prtGrid.outerHTML);
prtwin.document.close();
prtwin.focus();
prtwin.print();
prtwin.close();
}
</script>
<asp:Button ID="btnPrint" runat="server" Text="Print" OnClientClick="PrintGridData();"/>

How to get checkbox value in gridview in asp.net

I have a GridView and i am also using a checkbox in gridview that is like:
<asp:GridView ID="GridView2" CssClass="table table-striped table-hover" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="checkbox1" runat="server" Checked="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="SNo">
<ItemTemplate>
<%#Container.DataItemIndex+1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="GFname" HeaderText="Name" />
<asp:BoundField DataField="Address1" HeaderText="Address 1" />
<asp:BoundField DataField="Address2" HeaderText="Address 2" />
<asp:BoundField DataField="MobileNo" HeaderText="Mobile No" />
<asp:BoundField DataField="Location" HeaderText="Location" />
<asp:BoundField DataField="City" HeaderText="City" />
</Columns>
</asp:GridView>
cs
protected void btnsndwish_Click(object sender, EventArgs e)
{
foreach (GridViewRow g1 in GridView2.Rows)
{
CheckBox chk = (CheckBox)GridView2.FindControl("checkbox");
if (chk != null && chk.Checked)
{
string Query = "insert into SMSTable(MobileNo,MessageToSent,MessageDate,UserId,SentDate,Flag,GuestName) values ('" + g1.Cells[5].Text + "','" + txtmsg.Value + "','" + CurrentDate.ToString("dd-MMM-yyyy HH:mm:ss") + "','','" + CurrentDate.ToString("dd-MMM-yyyy HH:mm:ss") + "',0,'" + g1.Cells[2].Text + "')";
ds = obj.GetDataSet(Query);
}
ScriptManager.RegisterStartupScript(this, this.GetType(), "Success", "alert('MSG ');", true);
}
}
but all the time I debug the program and it showed that the checked checkbox value is also null.
It's not GridView2.FindControl("checkbox"); but g1.FindControl("checkbox");:
foreach (GridViewRow row in GridView2.Rows)
{
CheckBox chk = (CheckBox)row.FindControl("checkbox");
// ...
}
The NamingContainer(that is where each Id must be unique) is the GridViewRow not the whole GridView. FindControl doesn't search recursively.

how to dynamically add button in gridview cell

gridview cannot add an 'approve' button in gridview,can someone can help me thanks
http://i260.photobucket.com/albums/ii8/elvenchan2/rowAdd.png
behind code
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow dr in GridView2.Rows)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btn = new Button();
btn.Text = "Approve";
btn.ID = "Approve";
btn.Click += new EventHandler(Approve_Click);
if (dr.Cells[1].Text == "1")
{
dr.Cells[10].Controls.Add((Control)btn);
}
}
}
}
u must add a 10th cell at first
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
foreach (GridViewRow dr in GridView2.Rows)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btn = new Button();
btn.Text = "Approve";
btn.ID = "Approve";
btn.Click += new EventHandler(Approve_Click);
if (dr.Cells[1].Text == "1")
{
//Declare the bound field and allocate memory for the bound field.
ButtonField btnRent = new ButtonField();
//Initalize the DataField value.
btn.ItemStyle.HorizontalAlign = HorizontalAlign.Center;
btn.CommandName = "Button";
btn.ButtonType = ButtonType.Button;
btn.Text = "Rent";
btn.Visible = true;
//Add the newly created bound field to the GridView.
GridView2.Columns.Add(btn);
}
}
}
}
Since there is no criteria for creating the button, why not just make a TemplateField in your GridView markup and wire up a click handler or CommandName for the button, like this:
<asp:GridView id="GridView1" runat="server"
OnRowCommand="GridView1_RowCommand">
<Columns>
...
<asp:TemplateField>
<ItemTemplate>
<asp:Button id="ButtonApprove" runat="server"
CommandName="approve" Text="Approve" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Now in your code-behind, you can handle each individual approve button click, like this:
protected void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if(e.CommandName == "approve")
{
// Do approval logic here
}
}
You can try it:
if (e.Row.RowType == DataControlRowType.DataRow)
{
if (e.Row.RowState != DataControlRowState.Edit)
{
PlaceHolder ph = (PlaceHolder)e.Row.FindControl("PlaceHolder1");
Button b1 = new Button();
b1.ID = "Approve";
b1.Text = "Approve"
ph.Controls.Add(b1);
}
}
Of course, you should add a placeholder in the html template. like
<ItemTemplate>
<asp:PlaceHolder ID="PlaceHolder1" runat="server">
Button add here..
</asp:PlaceHolder>
</ItemTemplate>
Design
<asp:GridView ID="viewThemeTypeAssociationsGridView" runat="server" AutoGenerateColumns="False"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px"
CellPadding="3" CellSpacing="2"
OnRowDataBound="viewThemeTypeAssociationsGridView_RowDataBound"
DataSourceID="Sql_New" >
<Columns>
<asp:BoundField DataField="id" HeaderText="id" SortExpression="id"
InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Type" HeaderText="Type" SortExpression="Type" />
<asp:TemplateField HeaderText ="New Column" >
<ItemTemplate >
<asp:Button ID="btnnew" runat ="server" Visible ="false" ></asp:Button>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FFF1D4" />
<SortedAscendingHeaderStyle BackColor="#B95C30" />
<SortedDescendingCellStyle BackColor="#F1E5CE" />
<SortedDescendingHeaderStyle BackColor="#93451F" />
</asp:GridView>
<asp:SqlDataSource ID="Sql_New" runat="server"
ConnectionString="<%$ ConnectionStrings:EmployeeConnectionString %>"
SelectCommand="SELECT * FROM [tblnew]"></asp:SqlDataSource>
Code
protected void viewThemeTypeAssociationsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells[2].Text == " ")
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Button btnnew = (Button)e.Row.FindControl("btnnew");
btnnew.Visible = true;
}
}
}

asp can't detect the checked item in datagridview

I have a gridview with ckeck column,my user can select the item via checked box so i add a checkbox column to my gridview:
<asp:GridView ID="taminkonandeh" runat="server" CssClass="gv-list-company-col-edit" ShowHeaderWhenEmpty="True" AutoGenerateColumns="False" EnableModelValidation="True">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="ChTaminKonande" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="شماره " DataField="companyid" >
<HeaderStyle CssClass="gv-list-company-header" />
<ItemStyle CssClass="gv-list-company-col" />
</asp:BoundField>
<asp:BoundField HeaderText="نام شرکت " DataField="companyname">
<HeaderStyle CssClass="gv-list-company-header" />
<ItemStyle CssClass="gv-list-company-col" />
</asp:BoundField>
<asp:BoundField HeaderText="شماره ثبت " DataField="registrationNumber" >
<HeaderStyle CssClass="gv-list-company-header" />
<ItemStyle CssClass="gv-list-company-col" />
</asp:BoundField>
<asp:BoundField HeaderText="شماره اقتصادی" DataField="noEconomic" >
<HeaderStyle CssClass="gv-list-company-header" />
<ItemStyle CssClass="gv-list-company-col" />
</asp:BoundField>
</Columns>
<HeaderStyle CssClass="gv-list-company-header" />
<RowStyle CssClass="gv-list-company-row"/>
</asp:GridView>
and my code behind is :
for (int i = 0; i < taminkonandeh.Rows.Count; i++)
{
CheckBox chinvi = (CheckBox)taminkonandeh.Rows[i].FindControl("ChTaminKonande");
if (chinvi != null)
{
if (chinvi.Checked)
{
Count++;
comid = taminkonandeh.Rows[i].Cells[1].Text;
tblAnnouncePriceByCompany objanno = new tblAnnouncePriceByCompany();
objanno.letterId = objletter.letterId.ToString();
objanno.companyId = comid;
objanno.tenderId = Session["letterTenderId"].ToString();
db1.tblAnnouncePriceByCompanies.InsertOnSubmit(objanno);
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "myalert",
"alert('تامین کننده ای انتخاب نشده است ')", true);
return;
}
}
but "chinvi.Checked" condition is always false and i can't detect which checkboxs are selected.
This situation happens when you bind the gridview in pageload, and each postback rebinds it, removes posted value like this:
protected void Page_Load(object sender, EventArgs e)
{
//Code to get datasource
taminkonandeh.DataSource = myDataSource;
taminkonandeh.DataBind();
}
You need to change it to :
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
//Code to get datasource
taminkonandeh.DataSource = myDataSource;
taminkonandeh.DataBind();
}
}

image is not displaying in templatefield from gridview sorting

I have an issues with TemplateField in grid view.
There are two TemplateField(imgFSL,imgMain) show the Image based on value from database. In pageload, the grid view shows the correct image photo. After i click one of gridview column sorting, the grid does not show the image even the url is correct. Please help me this issue. I have searched other website and tried so many ways. But no resolved it yet after clicking grid view sorting.
Here is designer page for grid view
<asp:UpdatePanel ID="upBOMList" runat="server">
<ContentTemplate>
<asp:Panel ID="Panel2" runat="server" ScrollBars="Vertical" Height="350px">
<asp:GridView ID="grdBOMList" runat="server" AutoGenerateColumns="False"
AllowSorting="true" BorderStyle="Solid"
EmptyDataText="<%$ Resources:Resource, NoBOMListMsg %> " Font-Names="Verdana"
BorderWidth="1px" CellPadding="3" CellSpacing="1" GridLines="None" Width="100%"
BackColor="White" BorderColor="#999999" DataKeyNames="PartNo" ForeColor="Black"
OnSelectedIndexChanged="grdBOMList_SelectedIndexChanged" OnRowDataBound="grdBOMList_RowDataBound"
OnPageIndexChanging="grdBOMList_PageIndexChanging"
OnSorting="grdBOMList_Sorting" ShowFooter="False" >
<AlternatingRowStyle CssClass="gridAlternatingRowStyle" />
<Columns>
<asp:BoundField ControlStyle-BorderWidth="0" DataField="ItemLocationNo" HeaderText="<%$ Resources:Resource, LocID %>"
SortExpression="ItemLocationNo">
<ControlStyle BorderWidth="0px"></ControlStyle>
<ItemStyle CssClass="gridPaddingStyle_center" />
<HeaderStyle Width="50px" CssClass="gridPaddingStyle_center"></HeaderStyle>
</asp:BoundField>
<asp:BoundField ControlStyle-BorderWidth="0" DataField="PartCategory" HeaderText="<%$ Resources:Resource, Category %>"
SortExpression="PartCategory">
<ControlStyle BorderWidth="0px"></ControlStyle>
<ItemStyle CssClass="gridPaddingStyle_center" />
<HeaderStyle CssClass="gridPaddingStyle_center" Width="150px"></HeaderStyle>
</asp:BoundField>
<asp:ButtonField DataTextField="PartNo" HeaderText="<%$ Resources:Resource, PartNo %>"
ShowHeader="True" CommandName="Select" SortExpression="PartNo">
<ItemStyle CssClass="gridPaddingStyle_center" />
<HeaderStyle CssClass="gridPaddingStyle_center" Width="80px"></HeaderStyle>
</asp:ButtonField>
<asp:BoundField ControlStyle-BorderWidth="0" DataField="Description" HeaderText="<%$ Resources:Resource, Description %>"
SortExpression="Description">
<ControlStyle BorderWidth="0px"></ControlStyle>
<ItemStyle CssClass="gridPaddingStyle_left" />
<HeaderStyle CssClass="gridPaddingStyle_center" Width="150px"></HeaderStyle>
</asp:BoundField>
<asp:BoundField ControlStyle-BorderWidth="0" DataField="VDRCode" HeaderText="<%$ Resources:Resource, VendorsPN %>"
SortExpression="VDRCode">
<ControlStyle BorderWidth="0px"></ControlStyle>
<ItemStyle CssClass="gridPaddingStyle_left" />
<HeaderStyle CssClass="gridPaddingStyle_center" Width="80px"></HeaderStyle>
</asp:BoundField>
<asp:BoundField ControlStyle-BorderWidth="0" DataField="FSL" HeaderText="FSL">
<ControlStyle BorderWidth="0px"></ControlStyle>
<HeaderStyle CssClass="gridPaddingStyle_center" Width="150px"></HeaderStyle>
</asp:BoundField>
<asp:BoundField ControlStyle-BorderWidth="0" DataField="Main" HeaderText="<%$ Resources:Resource, Main %>">
<ControlStyle BorderWidth="0px"></ControlStyle>
<HeaderStyle CssClass="gridPaddingStyle_center" Width="150px"></HeaderStyle>
</asp:BoundField>
<asp:TemplateField HeaderText="FSL" HeaderStyle-Width="5%" ItemStyle-HorizontalAlign="Center"
FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="imgFSL" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="<%$ Resources:Resource, Main %>" HeaderStyle-Width="5%"
ItemStyle-HorizontalAlign="Center" FooterStyle-HorizontalAlign="Center">
<ItemTemplate>
<asp:Image ID="imgMain" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle CssClass="gridHeaderStyle" ForeColor="#ffffff" />
<FooterStyle CssClass="gridFooterStyle" ForeColor="Black" />
<PagerStyle CssClass="gridPagerStyle" ForeColor="#ffffff" />
<RowStyle CssClass="gridRowStyle" ForeColor="Black" />
<SelectedRowStyle BackColor="#2a2a7f" Font-Bold="False" ForeColor="White" />
</asp:GridView>
</asp:Panel>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnImportFile" />
<asp:PostBackTrigger ControlID="btnExportFile" />
<asp:PostBackTrigger ControlID="btnExport" />
<asp:PostBackTrigger ControlID="btnCreate" />
</Triggers>
Here is the coding porting for gridview row databound, sorting function and Create Table
public void grdBOMList_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Subsidiary sub = new SubsidiaryFacade().GetBySubsidiaryCode(userSubsidiaryCode, userid, userEntityCode);
int redInd = (int)sub.RedIndicatorQty;
int greenInd = (int)sub.GreenIndicatorQty;
string fsl = e.Row.Cells[5].Text;
string main = e.Row.Cells[6].Text;
System.Web.UI.WebControls.Image imgFSL = (System.Web.UI.WebControls.Image)e.Row.FindControl("imgFSL");
if (fsl != string.Empty && fsl != null)
{
int quantityFSL = Convert.ToInt32(fsl);
if (quantityFSL != null)
{
if (quantityFSL <= redInd)
{
imgFSL.ImageUrl = "~/image/Circle_Red.png";
//imgFSL.ImageUrl = ResolveUrl("~/image/Circle_Red.png");
//imgFSL.ImageUrl = Page.ResolveClientUrl("~/image/Circle_Red.png");
}
else if (redInd < quantityFSL && quantityFSL < greenInd)
{
imgFSL.ImageUrl = "~/image/Circle_Orange.png";
//imgFSL.ImageUrl = ResolveUrl("~/image/Circle_Orange.png");
//imgFSL.ImageUrl = Page.ResolveClientUrl("~/image/Circle_Orange.png");
}
else if (quantityFSL >= greenInd)
{
imgFSL.ImageUrl = "~/image/Circle_Green.png";
//imgFSL.ImageUrl = ResolveUrl("~/image/Circle_Green.png");
//imgFSL.ImageUrl = Page.ResolveClientUrl("~/image/Circle_Green.png");
}
}
}
if (main != string.Empty && main != null)
{
int quantityMain = Convert.ToInt32(main);
System.Web.UI.WebControls.Image imgMain = (System.Web.UI.WebControls.Image)e.Row.FindControl("imgMain");
if (quantityMain != null)
{
if (quantityMain <= redInd)
{
imgMain.ImageUrl = "~/image/Circle_Red.png";
}
else if (redInd < quantityMain && quantityMain < greenInd)
{
imgMain.ImageUrl = "~/image/Circle_Orange.png";
}
else if (quantityMain >= greenInd)
{
imgMain.ImageUrl = "~/image/Circle_Green.png";
}
}
}
}
}
This is grid sorting
protected void grdBOMList_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
string direction = string.Empty;
if (SortDirection == SortDirection.Ascending)
{
SortDirection = SortDirection.Descending;
direction = "DESC";
}
else
{
SortDirection = SortDirection.Ascending;
direction = "ASC";
}
BindBOMListGrid();
List<BOM> list = (List<BOM>)grdBOMList.DataSource;
DataTable dt = CreateDataTable_BOM();
if (list.Count > 0)
{
for (int i = 0; i < list.Count; i++)
{
BOM b = list[i];
DataRow row;
row = dt.NewRow();
row["ItemLocationNo"] = b.ItemLocationNo;
row["PartCategory"] = b.PartCategory;
row["PartNo"] = b.PartNo;
row["Description"] = b.Description;
row["VDRCode"] = b.VDRCode;
int fslvalue = Convert.ToInt32(b.FSL);
Subsidiary sub = new SubsidiaryFacade().GetBySubsidiaryCode(userSubsidiaryCode, userid, userEntityCode);
int redInd = (int)sub.RedIndicatorQty;
int greenInd = (int)sub.GreenIndicatorQty;
if (Convert.ToString(b.FSL) != string.Empty && b.FSL != null)
{
int quantityFSL = Convert.ToInt32(b.FSL);
if (quantityFSL != null)
{
if (quantityFSL <= redInd)
{
row["imgFSL"] = ResolveUrl("~/image/Circle_Red.png");
}
else if (redInd < quantityFSL && quantityFSL < greenInd)
{
row["imgFSL"] = ResolveUrl("~/image/Circle_Orange.png");
}
else if (quantityFSL >= greenInd)
{
row["imgFSL"] = ResolveUrl("~/image/Circle_Green.png");
}
}
}
dt.Rows.Add(row);
}
}
dt.DefaultView.Sort = sortExpression + " " + direction;
grdBOMList.DataSource = dt;
grdBOMList.DataBind();
ModalPopupExtender.Show();
}
This is Create data table for grid view
private DataTable CreateDataTable_BOM()
{
DataTable myDataTable = new DataTable();
DataColumn myDataColumn;
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "ItemLocationNo";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "PartCategory";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "PartNo";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "Description";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "VDRCode";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.Int32");
myDataColumn.ColumnName = "FSL";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.String");
myDataColumn.ColumnName = "imgFSL";
myDataTable.Columns.Add(myDataColumn);
myDataColumn = new DataColumn();
myDataColumn.DataType = Type.GetType("System.Int32");
myDataColumn.ColumnName = "Main";
myDataTable.Columns.Add(myDataColumn);
return myDataTable;
}
In pageload, the grid shows the image like that(before sorting)
After clicking one of grid column sorting, the image is not showing even the url is correct
Please give me any suggestions.
It may be because you have not registered any trigger of gridview events.
Try by adding a postback trigger for gridview. as:
<asp:PostBackTrigger ControlID="grdBOMList" />

Resources