In web application, I am trying to bind the Header Template of the gridivew, but i am not able to bind the data to gridview header.
<asp:GridView ID ="grdInner" runat ="server" AutoGenerateColumns ="false" >
<Columns >
<asp:TemplateField >
<HeaderTemplate >
<asp:Label ID="lblHeader" runat="server" Text='<%# Eval("title") %>'></asp:Label>
</HeaderTemplate>
<ItemTemplate >
<asp:Label ID ="lblDesc" runat ="server" Text ='<%# Eval("description") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Following code achieves the same things
<asp:GridView runat="server" ID="gridView" onrowdatabound="gridView_OnRowDataBound" AutoGenerateColumns="false">
<columns>
<asp:TemplateField>
<HeaderTemplate><asp:Label runat="server" ID="lblHeader"></asp:Label></HeaderTemplate>
</asp:TemplateField>
</columns>
</asp:GridView>
You can set label text in OnRowDataBound event
protected void gridView_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Header)
((Label)e.Row.FindControl("lblHeader") as Label).Text = "Your Data here";
}
Another way to do this that is fairly simple if you want to bind the DataTable column headers to the Gridview headers (for example, you are generating DataTables where the column names can be different and you want these dynamic names to be the GridView header column names).
DataTable dt = // Call your DataTable here.
// Get your column names here.
string nutrient = dt.Columns[2].ColumnName;
string nutrient1 = dt.Columns[3].ColumnName;
string nutrient2 = dt.Columns[4].ColumnName;
string nutrient3 = dt.Columns[5].ColumnName;
string nutrient4 = dt.Columns[6].ColumnName;
string nutrient5 = dt.Columns[7].ColumnName;
GridView1.DataSource = dt;
GridView1.DataBind();
if (GridView1.Rows.Count > 0)
{
GridView1.HeaderRow.Cells[2].Text = nutrient;
GridView1.HeaderRow.Cells[3].Text = nutrient1;
GridView1.HeaderRow.Cells[4].Text = nutrient2;
GridView1.HeaderRow.Cells[5].Text = nutrient3;
GridView1.HeaderRow.Cells[6].Text = nutrient4;
GridView1.HeaderRow.Cells[7].Text = nutrient5;
}
You can also do the same thing with the footer row using GridView1.FooterRow.Cells[x].Text = ...
Related
I have the below definition of a an Asp.net Gridview in a asp.net userControl.
<asp:GridView ID="grdTabularView" CssClass="standard HeadCenter rowborder cellborder" Width="100%"
runat="server" AlternatingRowStyle-CssClass="even"
HeaderStyle-CssClass="HeaderFreez"
AutoGenerateColumns="False" EnableModelValidation="True" Height="80px" onpageindexchanging="OnPaging">
<EmptyDataRowStyle/>
<Columns>
<%-- year
--%> <asp:TemplateField>
<HeaderTemplate>
Year:
<asp:DropDownList ID="ddlYear" runat="server"
OnSelectedIndexChanged = "YearChanged" AutoPostBack = "true"
AppendDataBoundItems = "true" >
<asp:ListItem Text = "ALL" Value = "ALL"></asp:ListItem>
</asp:DropDownList>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("Year")%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate>
<center class="bold">
No data available.
</center>
</EmptyDataTemplate>
<HeaderStyle CssClass="HeaderFreez" HorizontalAlign = "Center"></HeaderStyle>
<AlternatingRowStyle CssClass="even RowStyle"></AlternatingRowStyle>
</asp:GridView>
</div>
</td>
</tr>
</table>
Below is how i populated the DropDownList with a list of years to filter the grid data by.
private void BindYearList(DropDownList ddlYear)
{
ddlYear.DataSource = objDataTable.DefaultView;
ddlYear.DataTextField = "Year";
ddlYear.DataValueField = "Year";
ddlYear.DataBind();
ddlYear.Items.FindByValue(ViewState["YearFilter"].ToString()).Selected = true;
}
I want the function below to executed on the OnSelectedIndexChanged event of the DropDownList but it isn't firing.
protected void YearChanged(object sender, EventArgs e)
{
DropDownList ddlYear = (DropDownList)sender;
ViewState["YearFilter"] = ddlYear.SelectedValue;
objDataTable = drawChartGridOnly(htParameters, out dt, "");
myDataGrid.DataSource = objDataTable.DefaultView.RowFilter = string.Format("Field = '{0}'", ViewState["Filter"].ToString());
myDataGrid.DataBind();
}
I already have this OnSelectedIndexChanged = "YearChanged" AutoPostBack = "true" in the DropDownList's markup but is isn't making any diffference.
Does any one know what i could be doing wrong in the GridViews source above? The grid is in a .ascx user control.
Below is how i call BindYearList
DropDownList ddlYear = (DropDownList)grdTabularView.HeaderRow.FindControl("ddlYear");
this.BindYearList(ddlYear);
ddlYear.DataBind();
And below is how a bind the Grid
grdTabularView.DataSource = objDataTable.DefaultView ;
grdTabularView.DataBind();
grdTabularView.HeaderRow.Visible = true;
grdTabularView.Visible = true;
Please do not down vote. i am new to this site.
i tried myself but repeatedly the same error occurring.
protected void gvDepPayment_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label lbl = (Label)e.Row.FindControl("lblDeptName");
DataTable dT = (DataTable)ViewState["DataBounded"];
DataRow[] drows = dT.Select("DepartmentName = '" + lbl.Text + "'");
int Count = 0;
foreach (DataRow item in drows)
{
Count += Convert.ToInt32(item["PaidAmount"]);
}
Label lblPaidAmount = (Label)e.Row.FindControl("lblPaidAmount");
lblPaidAmount.Text = Count.ToString();
}
}
<asp:GridView ID="gvDepPayment" runat="server" AutoGenerateColumns="false"
OnRowDataBound="gvDepPayment_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Department Name">
<ItemTemplate>
<asp:Label ID="lblDeptName" runat="server" Text='<%#Eval("DepartmentName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Collection">
<ItemTemplate>
<asp:Label ID="lblPaidAmount" runat="server" Text="0"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
i want find the Payment list and show it in grid view like Department wise
This error message is caused by your reading the content of the DataRow at the column named PaidAmount, probably there are some null values in the set of rows returned by your query. In this scenario you could use the IsNull method of the DataRow class with the conditional operator. In the case of DBNull.Value you want to add zero to your count.
Count += item.IsNull("PaidAmount") ? 0 : Convert.ToInt32(item["PaidAmount"]);
I have the data displayed in the grid as follows:
StartDate Enddate Button
16/3/2013 17/3/2013 Signup---> this is an ASP button
18/3/2013 19/3/2012 Signup----> this is an ASP button
20/3/2012 20/3/2012 Signup----> this is an ASP button
I want asp.net with c# code when i clicked on first row signup button i want to get the data of the first row. If clicked on second row i want only the data of the second row startdate and end time. How can i acheive this? Please hep me in this regard.
In the asp button, Set properties: CommandName="SignUp" CommandArgument='<%# Container.DataItemIndex%>'
Now, when this button is clicked it calls Gridview's RowCommand Event
In that event e.CommandArgument contains your Row Number.
GridViewRow gvr= gvLinkImages.Rows[e.CommandArgument];
Now you can use gvr.Cells[column number] to get the particular text (Not recommended)
or use findcontrol to get the label or literal of the start/end date( assuming you are using Templatefields)
Sample code below
C#
protected void gvResults_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "SignUp")
{
int rwNumber = Convert.ToInt32(e.CommandArgument);
GridViewRow gvr = gvResults.Rows(rwNumber);
System.DateTime rowStartDate = default(System.DateTime);
System.DateTime rowEndDate = default(System.DateTime);
//If you are using Templatefields
Literal lblRowStartDate = gvr.FindControl("lblStartDate") as Literal;
Literal lblRowEndDate = gvr.FindControl("lblEndDate") as Literal;
rowStartDate = Convert.ToDateTime(lblRowStartDate.Text);
rowEndDate = Convert.ToDateTime(lblRowEndDate.Text);
//Incase you are not using TemplateFields or Autobinding your grid
rowStartDate = Convert.ToDateTime(gvr.Cells[0].Text);
rowEndDate = Convert.ToDateTime(gvr.Cells[1].Text);
}
}
ASPX
<asp:GridView runat="server" ID="gvResults" AutoGenerateColumns="false" OnRowCommand="gvResults_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Literal runat="server" ID="lblStartDate" Text='<%#Container.DataItem.StartDate%>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Literal runat="server" ID="lblStartDate" Text='<%#Container.DataItem.EndDate%>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" ID="btnSignUp" CommandName="SignUp" CommandArgument="<%# Container.DataItemIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
In asp.net application, I am using grid-view control in that I am binding the data to the label which is in grid-view.
If data is empty then the color of the row should be in red
If not I mean if data is there to bind then the row in green.
This is my code:
<asp:TemplateField HeaderText ="Holiday Region">
<ItemTemplate >
<asp:Label ID ="lblholdareg" runat ="server" Text ='<%# Eval("Holidaregion") %>' >
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
You need to handle the RowDataBound event, get into the e.Row item, and assign either a CSS class or directly set the background color. I prefer setting a CSS class so you can change the rendering of it without a recompile later.
<asp:GridView ID="GridView1" runat="server" OnRowDataBound="GridView1_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Holiday Region">
<ItemTemplate>
<asp:Label ID="lblholdareg" runat="server" Text='<%# Eval("Holidaregion") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the code-behind, I had to assume you were using a DataTable as your data source, update the code to fit your data structure:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
System.Data.DataRow row = (System.Data.DataRow)e.Row.DataItem;
if (row["Holidaregion"] == null || row["Holidaregion"].ToString().Trim().Length == 0)
{
e.Row.CssClass = "row-empty";
}
else
{
e.Row.CssClass = "row-full";
}
}
You can do it on rowdatabound function of gridview as follows
protected void RowDataBound(Object sender, GridViewRowEventArgs e)
{
if(e.Row.RowType == DataControlRowType.DataRow)
{
//change it according your cell number or find element
if(e.Row.Cells[0].Text != "")
e.Row.BackColor = Color.Green;
else
e.Row.BackColor = Color.Red;
}
}
if(e.Row.RowType == DataControlRowType.DataRow)
{
Control l = e.Row.FindControl("Label1");
((Label)l).BackColor = System.Drawing.Color.Red;
}
Try something like this
<asp:TemplateField HeaderText ="Holiday Region">
<ItemTemplate >
<asp:Label ID ="lblholdareg" runat ="server"
CSSClass='<%# (String.IsNullOrEmply(Eval("Holidaregion")))?"red:green" %>'
Text ='<%# Eval("Holidaregion") %>' >
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
Edit:
Instead of fighting with grid view inline and code behind stuffs, just use a jQuery and achieve the same in client side
try it this code it is every row in color change with the category wise or filters wise
http://devloper4u.blogspot.in/2013/10/how-to-set-color-in-every-row-on.html
I have a grid view where some of the rows have attached pictures. when I press Button2 I pull information from the sql record, about which folder on the server that has the pictures.
This works already, but I can not get the button to only be visible in the rows that have image folder attached.
I've googled a long time and found different solutions similar to the following, but I can not get it to work.
What am I doing wrong?
<asp:SqlDataSource ID="SqlDSodinRSSfeb" runat="server"
ConnectionString="<%$ ConnectionStrings:herning_brand_dk_dbConnectionString %>"
SelectCommand="SELECT PubDateTime, Melding, Station, PhotoFolder FROM OdinRSS ">
</asp:SqlDataSource>
<asp:GridView ID="GridView14" runat="server" DataSourceID="SqlDSodinRSSfeb"
AutoGenerateColumns="False" Width="500px" OnRowCommand="Button_RowCommand" >
<Columns>
<asp:BoundField DataField="PubDateTime" HeaderText="Tidspunkt" />
<asp:BoundField DataField="Melding" HeaderText="Melding for udkaldet" />
<asp:BoundField DataField="Station" HeaderText="Station" />
<asp:TemplateField HeaderText="Foto" >
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("PhotoFolder") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="Button2" runat="server" Text="Foto" Visible='<%# Eval("PhotoFolder") != "Null" %>'
CommandName="ButtonClick" CommandArgument='<%# Eval("PhotoFolder") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
My .cs
protected void Button_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandArgument != null)
{
switch (e.CommandName)
{
case "ButtonClick":
{
int Folder = Convert.ToInt32(e.CommandArgument);
PhotoList(Folder);
}
break;
}
}
}
void PhotoList(int FolderNumber)
{
var imagePaths = Directory.GetFiles(Server.MapPath("PhotoFolder\\" + FolderNumber));
var imageNames = new string[imagePaths.Length];
for (int i = 0; i < imagePaths.Length; i++)
{
imageNames[i] = imagePaths[i].Substring(imagePaths[i].LastIndexOf("\\") + 1);
}
var dt = new DataTable();
dt.Columns.Add("ImageName", typeof(string));
dt.Columns.Add("ImagePath", typeof(string));
foreach (var imgName in imageNames)
{
DataRow dr = dt.NewRow();
dr["ImageName"] = RemoveExtension(imgName);
dr["ImagePath"] = "PhotoFolder/" + FolderNumber + "/" + imgName;
dt.Rows.Add(dr);
}
DataList1.DataSource = dt;
DataList1.DataBind();
}
string RemoveExtension(string imgName)
{
return imgName
.Replace(".jpg", "")
.Replace(".png", "");
}
The sql field "PhotoFolder" is a nvarchar(50). If there is photos for the record, the field has a number from 100 and up, that refares to the folder containing photos. If there are no photo for the record, the field contains "Null"
I have also tried:
<asp:Button ID="Button2" runat="server" Text="Foto" Visible='<%# Eval("PhotoFolder").ToString() != "Null" %>'
But the button is shown in all rows, not just the ones that has a string(number) in "PhotoFolder"
It can be achieved simple in Inline code
<asp:ImageButton ID="ibtnBranchType1" runat="server" ImageUrl='<%# "~/images/" + Eval("branchtype1")+".png" %>' Visible='<%# Convert.ToString(Eval("branchtype1"))=="" ? false : true %>' Height="20px"/>
Here Eval("branchtype1") we are getting value of id from data table like 1, 2, 3 etc. and our image folder consists images like 1.png, 2.png, 3.png etc.,
Visible='<%# Convert.ToString(Eval("branchtype1"))=="" ? false : true %>'
if value doesn't contain any id it will get null. we will compare it with empty string using ternary operator.
Try this.
Markup
Visible='<%# HideEmptyPhotoFolder(Eval("PhotoFolder")) %>'
Code-Behind
protected bool HideEmptyPhotoFolder(object photoFolder)
{
return photoFolder != null && !String.IsNullOrEmpty(photoFolder.ToString());
}
You can simply do that in GridView RowDataBound event.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.rowdatabound.aspx
As per your question you should write the code for checking the rows containing the image,
you can write the code in RowDatabound event,and set visible property of button to false on that row which doesn't contain image.