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" />
Related
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);
}
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();"/>
I am trying to calculate the date difference between two dates and want to show them in grid. I have created a table in the grid and the results can be printer there.
My RowDataBound is calculating everything but don't know how to print the results.
protected void grdADR_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lblADRYear = (Label)e.Row.FindControl("lblADRYear");
Label lblBRCIDADR = (Label)e.Row.FindControl("lblBRCIDADR");
DataTable dt = new DataTable();
string strQuery = "Select ADR_TYPE,DatePART(dayofyear,Document_Date) AS DayOfTheYearADR,Document_Date From ADR Where BRCID = '" + lblBRCIDADR.Text.ToString() + "'"
+ " AND CAST(YEAR(Document_Date) AS VARCHAR(4)) = '" + lblADRYear.Text.ToString() + "' Order by DayOfTheYearADR";
dt = objAccess.GetDataTable(strQuery);
if (dt != null)
{
if (dt.Rows.Count > 0)
{
int DayMarker = 0;
int LastDay = 0;
List<Label> labels = new List<Label>();
for (int rcnt = 0; rcnt < dt.Rows.Count; rcnt++)
{
DataRow dr = dt.Rows[rcnt];
Label lblADRTimeLineStart = new Label();
lblADRTimeLineStart.ForeColor = System.Drawing.Color.Red;
int RowDay = int.Parse(dr["DayOfTheYearADR"].ToString());
if (LastDay != RowDay)
{
Label lblEmptyBlock = new Label();
lblADRTimeLineStart.ForeColor = System.Drawing.Color.Blue;
lblEmptyBlock.Width = (RowDay - DayMarker) * 3;
labels.Add(lblEmptyBlock);
Label lblADRBlock = new Label();
lblADRTimeLineStart.ForeColor = System.Drawing.Color.Green;
lblADRBlock.Width = 3;
labels.Add(lblADRBlock);
DayMarker = RowDay + 3;
}
LastDay = RowDay;
}
}
}
}
}
ASPX File
<asp:GridView ID="grdADR" runat="server" DataSource='<%# functADRTimeLine(Eval("Month").ToString()) %>' AutoGenerateColumns="false" ShowHeader="true" AllowPaging="false" Width="1260px" GridLines="Both"
BorderWidth="0" BorderColor="#839168" BorderStyle="Solid" CellPadding="0" BackColor="white" OnRowDataBound="grdADR_RowDataBound">
<Columns>
<asp:TemplateField Visible="false">
<HeaderTemplate>BRCID</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblBRCIDADR" runat="server" Text='<%# Bind("BRCID") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="0px" Wrap="true" BorderColor="black" BorderStyle="Dotted" BorderWidth="1" HorizontalAlign="Center" />
<HeaderStyle BorderColor="black" BorderStyle="Outset" BorderWidth="1" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField Visible="false">
<HeaderTemplate>Year</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblADRYEAR" runat="server" Text='<%# Bind("ADR_YEAR") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="0px" Wrap="true" BorderColor="black" BorderStyle="Dotted" BorderWidth="1" HorizontalAlign="Center" />
<HeaderStyle BorderColor="black" BorderStyle="Outset" BorderWidth="1" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td style="width: 150px">
<%--HERE I WANT TO PRINT MY RESULTS.--%>
</td>
<td style="width: 1101px"></td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle Height="25px" HorizontalAlign="Center" BackColor="#a8b194" />
<RowStyle CssClass="grd_RowStyle" BorderColor="black" BorderStyle="Dotted" BorderWidth="1" Wrap="true" />
</asp:GridView>
There are many options for you to print the text
One option would be
Add a placeholder control in where you want the labels to be printed
<asp:PlaceHolder ID="placeHolderLabels" runat="server"></asp:PlaceHolder>
In the codebehind, find this placeholder like this
PlaceHolder placeHolderLabels= (PlaceHolder)e.Row.FindControl("placeHolderLabels");
Then add your labels to this placeholder control using the following code
placeHolderLabels.Controls.Add(lblEmptyBlock);
placeHolderLabels.Controls.Add(lblADRBlock);
Another option is, since you are printing table like structure, you can add a datalist/gridview/repeater control where you want to print the labels. Then you can bind your calculated list to this control, which is more cleaner
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;
}
}
}
I have two dropdownlists that are used to generate a gridview that will be edited and updated. I am lost as to why the gridview will not populate. I am enclosing the coded that I have. I have tried hiddenfields, I have parameters right now that seem to be populating correctly, I am just very confused as to why I can't see the gridview. As a caveat, I need to be able to update the certain columns in the rows either by text box or dropdownlist. If I change the query on the datasource for the gridview to bring in every row I have in the database, I can see everything and edit and update perfectly.
Here is the code first my aspx then the aspx.cs
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Annos3.aspx.cs" Inherits="SHCAnnotation.WebForm2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="dlJobName" runat="server" AutoPostBack="True"
DataSourceID="JobName" DataTextField="Name" DataValueField="Name"
style="z-index: 1; left: 25px; top: 50px; position: absolute; bottom: 257px; height: 45px; width: 242px;"
onselectedindexchanged="dlJobName_SelectedIndexChanged" >
</asp:DropDownList>
<asp:SqlDataSource ID="JobName" runat="server"
ConnectionString="<%$ ConnectionStrings:SRM_MetricConnectionString %>"
SelectCommand="SELECT DISTINCT Name FROM vw_GridviewSource WHERE (DueDt > sysdatetime()) ORDER BY Name">
</asp:SqlDataSource>
<asp:GridView ID="gvSummary" runat="server" AutoGenerateColumns = "False" AllowSorting = "true"
OnRowCancelingEdit = "CancelEdit" OnRowEditing = "EditSummary" OnRowDataBound = "RowDataBound"
OnRowUpdating = "UpdateSummary" CellPadding="4" ForeColor="#333333"
GridLines="None" DataKeyNames="AnnotationNumber, Cust, Name, AnnotationDate"
style="z-index: 1; left: 10px; top: 130px; position: absolute; height: 133px; width: 257px" >
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<columns>
<asp:CommandField ShowEditButton="true" />
<asp:TemplateField HeaderText = "Annotation Number">
<ItemTemplate>
<asp:Label ID = "lblAnno" runat="server" Text='<%# Eval("AnnotationNumber") %>'> </asp:Label>
</ItemTemplate>
<HeaderStyle Width="300px" />
<ItemStyle Width="300px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "Annotation By" HeaderStyle-Width = "250">
<ItemTemplate>
<asp:Label ID = "lblAnnoBy" runat="server" Text='<%# Eval("AnnotationBy") %>' Width = "150"> </asp:Label>
</ItemTemplate>
<HeaderStyle Width="450" />
<ItemStyle Width="450" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "Annotation Type">
<ItemTemplate>
<asp:Label ID = "lblAnnoType" runat="server" Text='<%# Eval("AnnotationType") %>' Width = "150"> </asp:Label>
</ItemTemplate>
<HeaderStyle Width="450px" />
<ItemStyle Width="450px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "Business Unit" HeaderStyle-Width = "250">
<ItemTemplate>
<asp:Label ID = "lblBU" runat="server" Text='<%# Eval("Unit") %>' Width = "250" ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblBU" runat="server" Text='<%# Eval("Unit") %>' Visible ="false"></asp:Label>
<asp:DropDownList ID = "dlBU" runat="server" AutoPostBack = "true">
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle Width="300px" HorizontalAlign="Center" />
<ItemStyle Width="300px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "Error Type" HeaderStyle-Width = "250">
<ItemTemplate>
<asp:Label ID = "lblET" runat="server" Text='<%# Eval("ErrorType") %>' Width = "250" ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblET" runat="server" Text='<%# Eval("ErrorType") %>' Visible ="false"></asp:Label>
<asp:DropDownList ID = "dlET" runat="server" AutoPostBack = "true">
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle Width="300px" HorizontalAlign="Center" />
<ItemStyle Width="300px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "Actual Agency Error" HeaderStyle-Width = "250">
<ItemTemplate>
<asp:Label ID = "lblAA" runat="server" Text='<%# Eval("ActualAgencyError") %>' Width = "250" ></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lblAA" runat="server" Text='<%# Eval("ActualAgencyError") %>' Visible ="false"></asp:Label>
<asp:DropDownList ID = "dlAA" runat="server" AutoPostBack = "true">
</asp:DropDownList>
</EditItemTemplate>
<HeaderStyle Width="300px" HorizontalAlign="Center" />
<ItemStyle Width="300px" HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText = "AnnotationComments">
<ItemTemplate>
<asp:Label ID = "lblAnnoComm" runat ="server" Text = '<%# Eval("AnnotationComments") %>' Width = "400"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = "sgk Comments">
<ItemTemplate>
<asp:Label ID = "lblsgkComm" runat ="server" Text = '<%# Eval("sgkComments") %>' Width = "400"></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Textbox ID="tbsgkComm" runat="server" Text='<%# Eval("sgkComments") %>' TextMode = "MultiLine" Columns = "40" ></asp:Textbox>
</EditItemTemplate>
<HeaderStyle HorizontalAlign="Center" Width="400px" />
<ItemStyle HorizontalAlign="Justify" Width="400px" />
</asp:TemplateField>
</columns>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
</div>
<asp:DropDownList ID="dlStage" runat="server" AutoPostBack="True"
DataSourceID="Stage" DataTextField="Annotation_Date"
DataValueField="Annotation_Date" Height="45px"
style="z-index: 1; left: 360px; top: 50px; position: absolute"
Width="240px" onselectedindexchanged="dlStage_SelectedIndexChanged">
</asp:DropDownList>
<asp:SqlDataSource ID="Stage" runat="server"
ConnectionString="<%$ ConnectionStrings:SRM_MetricConnectionString %>"
SelectCommand="SELECT DISTINCT [AnnotationDate] AS Annotation_Date FROM [vw_GridviewSource] WHERE ([Name] = #Name)">
<SelectParameters>
<asp:ControlParameter ControlID="dlJobName" Name="Name"
PropertyName="SelectedValue" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:HiddenField ID = "hfJN" runat="server" />
<asp:HiddenField ID = "hfST" runat="server" />
</form>
</body>
</html>
aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Security;
using System.Configuration;
namespace SHCAnnotation
{
public partial class WebForm2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//hfJN.Value = dlJobName.SelectedIndex.ToString();
//hfST.Value = dlStage.SelectedIndex.ToString();
//this.BindDataInit();
}
}
protected void EditSummary(object sender, GridViewEditEventArgs e)
{
gvSummary.EditIndex = e.NewEditIndex;
BindData();
}
protected void CancelEdit(object sender, GridViewCancelEditEventArgs e)
{
gvSummary.EditIndex = -1;
BindData();
}
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && gvSummary.EditIndex == e.Row.RowIndex)
{
DropDownList dlBU = (DropDownList)e.Row.FindControl("dlBU");
string Cust = gvSummary.DataKeys[e.Row.RowIndex].Values["Cust"].ToString();
string BUquery = "select distinct Unit from vw_BU where Business ='" + Cust + "'";
SqlCommand BUcmd = new SqlCommand(BUquery);
dlBU.DataSource = GetData(BUcmd);
dlBU.DataTextField = "Unit";
dlBU.DataValueField = "Unit";
dlBU.DataBind();
dlBU.Items.FindByValue((e.Row.FindControl("lblBU") as Label).Text).Selected = true;
DropDownList dlET = (DropDownList)e.Row.FindControl("dlET");
string ETquery = "select distinct ErrorType from ErrorType";
SqlCommand ETcmd = new SqlCommand(ETquery);
dlET.DataSource = GetData(ETcmd);
dlET.DataTextField = "ErrorType";
dlET.DataValueField = "ErrorType";
dlET.DataBind();
dlET.Items.FindByValue((e.Row.FindControl("lblET") as Label).Text).Selected = true;
DropDownList dlAA = (DropDownList)e.Row.FindControl("dlAA");
string AAquery = "select distinct AAA from ActualAgencyError";
SqlCommand AAcmd = new SqlCommand(AAquery);
dlAA.DataSource = GetData(AAcmd);
dlAA.DataTextField = "AAA";
dlAA.DataValueField = "AAA";
dlAA.DataBind();
dlAA.Items.FindByValue((e.Row.FindControl("lblAA") as Label).Text).Selected = true;
}
}
protected void UpdateSummary(object sender, GridViewUpdateEventArgs e)
{
string BU = (gvSummary.Rows[e.RowIndex].FindControl("dlBU") as DropDownList).SelectedItem.Value;
string ET = (gvSummary.Rows[e.RowIndex].FindControl("dlET") as DropDownList).SelectedItem.Value;
string AA = (gvSummary.Rows[e.RowIndex].FindControl("dlAA") as DropDownList).SelectedItem.Value;
string AnnotationNumber = gvSummary.DataKeys[e.RowIndex].Value.ToString();
string sgkComments = (gvSummary.Rows[e.RowIndex].FindControl("tbsgkComm") as TextBox).Text;
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
string query = "update vw_GridviewSource set [BusinessUnit] = #BU, [ErrorType] = #ET, [sgkComments] = #sgk, [ActualAgencyError] = #AA where [AnnotationNumber] = #AnnoNum";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#BU", BU);
cmd.Parameters.AddWithValue("#AnnoNum", AnnotationNumber);
cmd.Parameters.AddWithValue("#ET", ET);
cmd.Parameters.AddWithValue("#AA", AA);
cmd.Parameters.AddWithValue("#sgk", sgkComments);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
}
private void BindDataInit()
{
SqlCommand cmd = new SqlCommand();
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.Connection = con;
cmd.CommandText = "select [AnnotationNumber],[AnnotationBy],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust,Name,AnnotationDate from vw_GridviewSource" ;
gvSummary.DataSource = GetData(cmd);
gvSummary.DataBind();
}
private void BindData()
{
string selectedName = dlJobName.SelectedValue;
string selectedStage = dlStage.SelectedValue;
//SqlCommand cmd = new SqlCommand(query);
SqlCommand cmd = new SqlCommand();
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
cmd.Connection = con;
cmd.CommandText = "select [AnnotationNumber],[AnnotationBy],[AnnotationType],[BusinessUnit] as Unit,[ErrorType],[ActualAgencyError],AnnotationComments,[sgkComments],[ActualAgencyError],Cust,Name,AnnotationDate from vw_GridviewSource where Name = #p1 and AnnotationDate = #p2";
//cmd.Parameters.AddWithValue("#p1",selectedName);
//cmd.Parameters.AddWithValue("#p2",selectedStage);
gvSummary.DataSource = GetData(cmd);
gvSummary.DataBind();
}
private DataTable GetData(SqlCommand cmd)
{
string selectedName = dlJobName.SelectedValue;
string selectedStage = dlStage.SelectedValue;
string strConnString = ConfigurationManager.ConnectionStrings["SRM_MetricConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("#p1",selectedName);
cmd.Parameters.AddWithValue("#p2",selectedStage);
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
return dt;
}
}
}
}
protected void dlJobName_SelectedIndexChanged(object sender, EventArgs e)
{
//string JobName = Application["gJob"].ToString();
BindData();
}
protected void dlStage_SelectedIndexChanged(object sender, EventArgs e)
{
//string stage = Application["gStage"].ToString();
BindData();
}
}
}