data Grid Data bound field header text change in c# - c#

I have a datagrid that has a BoundColumn there I am trying to change the header text on page load I so fa. I have tried this.
<asp:datagrid id="dgdata" runat="server" Width="658px" CellPadding="2" PageSize="2" DataKeyField="Name"
AutoGenerateColumns="False" ShowFooter="True" BorderColor="AliceBlue" OnItemDataBound="dgTranscript_ItemDataBound">
<Columns>
<asp:BoundColumn DataField="Name" HeaderText="" ItemStyle-VerticalAlign="Top"></asp:BoundColumn>
</Columns>
</asp:datagrid>
C#
dgdata.Columns[1].Visible = true;
dgdata.Columns[1].HeaderText = lblAverage.Text
I want to set the text to be the text that's inside that label but its not letting me if i say without the label it works
dgdata.Columns[1].Visible = true;
dgdata.Columns[1].HeaderText = "Some Text";
Binding Data
DataSet ds;
DataRow drClient = null;
dgdata.Columns[1].HeaderText = lblAverage.Text; // Here before the Daatabind I set the text to be that label
DataConn.WebExecute(out ds);
DataConn.Bind(dgTranscript, ds);// This binds the data to the datagrid
It shows that text as the header but when I try punting in any string or a label text it denies the whole header disappears
Thanks in advance. Best Regards

If the value of lblAverage is set after calling DataBind on the datagrid then the header will remain empty.
This works
lblAverage.Text = "Some Text";
dgdata.Columns[0].HeaderText = lblAverage.Text;
dgdata.DataSource = mySource;
dgdata.DataBind();
While this will not
lblAverage.Text = "Some Text";
dgdata.DataSource = mySource;
dgdata.DataBind();
dgdata.Columns[0].HeaderText = lblAverage.Text;

You can try this.
<asp:Label ID="lblAverage" runat="server" Text="Header Value"></asp:Label>
<asp:DataGrid ID="dgdata" runat="server" Width="658px" CellPadding="2" PageSize="2" DataKeyField="Name"
AutoGenerateColumns="False" ShowFooter="true" ShowHeader="true" BorderColor="AliceBlue">
<Columns>
<asp:TemplateColumn>
<HeaderTemplate>
<asp:Label ID="lblheader" runat="server" Text='<%# lblAverage.Text %>'></asp:Label>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lblvalue" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateColumn>
</Columns>
</asp:DataGrid>

Related

Cell Text Always &nbsp:

I want to display the text of a specific cell in a textbox whenever I select a row from my gridview but whenever i do this "&nbsp" is the only text that I get even though the cell is not empty. Data on the gridview is bound from my database and I made a function where all the data from my database will be bound on my gridview. Below is the code that I'm using.
textbox1.Text = myGridView.SelectedRow.Cells[3].Text;
Markup
<asp:GridView ID="TraineeGrid" runat="server" AutoGenerateSelectButton ="true" AllowSorting="True" ShowHeader="true"
ShowFooter="false" AutoGenerateColumns="False" AutoGenerateEditButton="false" ScrollBars="Auto"
OnRowEditing="TraineeGrid_RowEditing"
OnRowUpdating="TraineeGrid_RowUpdating" OnRowCancelingEdit="TraineeGrid_RowCancelingEdit"
DataKeyNames="ID" Width="100%"
CellPadding="4" ForeColor="#333333" GridLines="None" HorizontalAlign="Center"
EditRowStyle-VerticalAlign="Middle" OnInit="Page_Load" OnRowDataBound="TraineeGrid_RowDataBound" OnSelectedIndexChanging="TraineeGrid_SelectedIndexChanging" OnSelectedIndexChanged="TraineeGrid_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="Delegates Name">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbDelegate" runat="server" Text="Delegate Name" CommandName="Sort"
CommandArgument="Delegate" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newDelegate" TabIndex="1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("Delegate") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDelegate" runat="server"
Text='<%# Eval("Delegate") %>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Rank/Position">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbRankPos" runat="server" Text="Rank/Position" CommandName="Sort"
CommandArgument="RankPos" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newRankPos" TabIndex="2" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("RankPos") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtRankPos" runat="server"
Text='<%# Eval("RankPos") %>'/>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
Function that binds Data
private void PopulateData()
{
DataTable dataTable = new DataTable();
using (SqlConnection connection = new SqlConnection(WebConfigurationManager.ConnectionStrings["TestCS"].ConnectionString))
{
string path = "PopulateSQL.txt";
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
}
string sql = sb.ToString();
using (SqlCommand cmd = new SqlCommand(sql, connection))
{
using (SqlDataAdapter dataAdapt = new SqlDataAdapter(cmd))
{
dataAdapt.Fill(dataTable);
ViewState["NormalGrid"] = dataTable;
}
}
}
}
if (dataTable.Rows.Count > 0)
{
TraineeGrid.DataSource = dataTable;
TraineeGrid.DataBind();
}
else
{
//Displays 'No Data Found' to gridview if there are no data in table
dataTable.Rows.Add(dataTable.NewRow());
TraineeGrid.DataSource = dataTable;
TraineeGrid.DataBind();
TraineeGrid.Rows[0].Cells.Clear();
TraineeGrid.Rows[0].Cells.Add(new TableCell());
TraineeGrid.Rows[0].Cells[0].ColumnSpan = dataTable.Columns.Count;
TraineeGrid.Rows[0].Cells[0].Text = "No Data Found";
TraineeGrid.Rows[0].Cells[0].HorizontalAlign = HorizontalAlign.Center;
}
}
You can use this: textbox1.Text = Server.HtmlDecode(row.Cells[1].Text.Trim());
In OnSelectedIndexChanged :
protected void OnSelectedIndexChanged1(object sender, EventArgs e)
{
//Get the selected row
GridViewRow row = GridView1.SelectedRow;
if (row != null)
{
// With
// TextBox1.Text = (row.FindControl("lblLocalTime") as Label).Text;
// Without
TextBox1.Text = Server.HtmlDecode(row.Cells[1].Text.Trim());
}
}
Complete Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
OnSelectedIndexChanged="OnSelectedIndexChanged1" AutoGenerateSelectButton="true">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="City" HeaderText="City" ItemStyle-Width="150" />
</Columns>
I've already found a solution. The problem is Im using TemplateField instead of BoundField that's why I cant use .Cells[] to get the specific cell that I wanted to get. However, if you are using TemplateField you can use .FindControl() and put in the ID of the label where your binding of data happens (ex. Text ='<%# Eval("FirstName") %>'). You can see that I put label on ItemTemplate to call it's ID.
Markup
<asp:TemplateField HeaderText="Delegates Name">
<ItemStyle HorizontalAlign="Center" Width="125px" />
<HeaderTemplate>
<asp:LinkButton ID="lbDelegate" runat="server" Text="Delegate Name" CommandName="Sort"
CommandArgument="Delegate" ForeColor="White" Font-Underline="False"></asp:LinkButton>
<br />
<asp:TextBox ID="newDelegate" TabIndex="1" runat="server"></asp:TextBox>
</HeaderTemplate>
<ItemTemplate>
<asp:Label ID="lbName" runat="server" Text = '<%# Eval("Delegate") %>'> </asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtDelegate" runat="server"
Text='<%# Eval("Delegate") %>' />
</EditItemTemplate>
</asp:TemplateField>
Code Behind
Label varName = (Label)rows.FindControl("lbName");
string name = varName.Text;

Getting value of a cell from a GridView on SelectedIndexChanged event of DropDownList

I have a GridView that has data bounded rows. I'm trying to get specific cell value on the SelectedIndexChanged event of DropDownList. My tries are as follows:
string temp= GridView2.SelectedRow.Cells[3].Text;
string temp = ((DataBoundLiteralControl)GridView2.Rows[0].Cells[3].Controls[0]).Text;
DataBoundLiteralControl dblc = (DataBoundLiteralControl)GridView2.Rows[0].Cells[3].Controls[0];
string temp=dblc.Text;
These all 3 of them returns null.
Moreover, the Control[0] is returning correct value of TemplateFields only, but not DataBound fields.
.aspx
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor=" #d54d7b" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#FFFAFC" AlternatingRowStyle-BackColor="#FFFFF7" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" AllowPaging="true" OnPageIndexChanging="OnPageIndexChanging" Width="900px" Font-Names="Segoe UI Light" BorderColor="#DEDEDE">
<RowStyle HorizontalAlign="center" />
<Columns>
<asp:BoundField DataField="Description" HeaderText="Description" ItemStyle-Width="80" />
<asp:BoundField DataField="Vacancies" HeaderText="Vacancies" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Detail">
<ItemTemplate>
<asp:BoundField DataField="Date" HeaderText="Date" ItemStyle-Width="80" />
<asp:BoundField DataField="Time" HeaderText="Time" ItemStyle-Width="80" />
</Columns>
Problem you are probably facing is that, GridView1 hasn't been bounded yet.. that is the reason why Control[0] is returning correct value of TemplateFields but cells in the gridview returns null.
You can do the following
protected void ddl_SelectedIndexChanged(object sender, EventArgs e)
{
/// send value to filter or bind gridView1
/// bind gridvew
string temp = GridView1.Rows[0].Cells[3].Text;
/// or any code to get values from GridView Cell
}
I Converted all <asp:BoundFields> to <asp:TemplateField> and it looked like this:
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor=" #009C0D" HeaderStyle-ForeColor="White"
RowStyle-BackColor="#FFFAFC" AlternatingRowStyle-BackColor="#FFFFF7" AlternatingRowStyle-ForeColor="#000"
AutoGenerateColumns="false" AllowPaging="true" CssClass="test"
HtmlEncode="true"
Font-Names="Segoe UI Light" BorderColor="#DEDEDE" >
<RowStyle HorizontalAlign="center" />
<Columns>
<asp:TemplateField HeaderText="Description" ControlStyle-Width="250px" ><ItemTemplate> <asp:LinkButton ID= "Description" PostBackUrl='<%# Eval("Description", "~/{0}.aspx") %>' Text='<%# Eval("Description")%>' runat="server" ></asp:LinkButton> </ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Vacancies"><ItemTemplate> <asp:Label ID="Vacancies" Text='<%# Eval("Vacancies")%>' runat="server" ></asp:Label> </ItemTemplate></asp:TemplateField>
<asp:TemplateField HeaderText="Detail"><ItemTemplate><asp:Label ID="City" Text='<%# Eval("City")%>' runat="server" ></asp:Label> <div style="font-size:10px"> <asp:Label ID="Label1" Text='<%# Eval("DateDay")%>' runat="server" ></asp:Label> </div> </ItemTemplate></asp:TemplateField>
//and others
</Columns>
</asp:GridView>
And get specific value by entering this code behind DropDownList:
if (dropdown.SelectedIndex != -1)
{
ListItem mySelectedItem = (from ListItem li in dropdown.Items where li.Selected == true select li).First();
foreach (GridViewRow rw in GridView2.Rows)
{
Label tv = (Label)rw.Cells[3].FindControl("City");
if (tv.Text.IndexOf(mySelectedItem.Text) != -1)
{
rw.Visible = true;
}
else
rw.Visible = false;
}
}

To add new row in gridview using javascript

In the below code i have gridview which has textbox and dropdownlist i want to add rows using javascript.My aim is to avoid postback on adding rows.
Markup code:
<asp:GridView runat="server" ID="gvProduct" AutoGenerateColumns="false"
Width="100%" CellPadding="4" ForeColor="#333333" ShowFooter="true"
PageSize-Mode="NumericPages" PagerStyle-Visible="true" AllowPaging="false" AllowSorting="true"
CssClass="mGrid" PagerStyle-CssClass="pgr" AlternatingRowStyle-CssClass="alt"
OnRowDataBound="gvProduct_RowDataBound" OnRowCommand="gvProduct_RowCommand" OnRowDeleting="gvProduct_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="Product Name" ItemStyle-Width="350px">
<ItemTemplate>
<asp:DropDownList ID="ddlProduct" runat="server" AutoPostBack="false" Style="width: 100%; height:23px" ></asp:DropDownList>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Current Stock" ItemStyle-Width="80px" Visible="false">
<ItemTemplate>
<asp:Label ID="lblCurrentStock" runat="server" onkeypress="return isNumberKey(event, false);" Height="20px" style="width:80px" Enabled="false" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Quantity" ItemStyle-Width="80px">
<ItemTemplate>
<asp:TextBox ID="txtQuantity" onkeypress="return isNumberKey(event, false);" runat="server" Height="20px" Width="150px" onblur="js_function(this);" > </asp:TextBox>
<asp:Label ID="lblunittype" runat="server" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button2" OnClientClick="AddRow(); return false;" runat="server" Text="Button" />
Javascript code:
function AddRow() {
var table = document.getElementById('<%=gvProduct.ClientID %>');
var newRow = table.insertRow();
var i = 0;
for (i = 0; i < table.rows[0].cells.length; i++) {
var newCell = newRow.insertCell();
newCell.innerHTML = 'New Row';
}
}
Gridview in asp = Table in HTML
new row in Gridview in asp = new row in Table in HTML
Sample JavaScript code:
function AddRow() {
let tableRef = document.getElementById('MainContent_gvItems');
let newRow = tableRef.insertRow(-1);//inserts at last row
let Cell0 = newRow.insertCell(0);
let Text0 = document.createTextNode('mydata');
Cell0.appendChild(Text0);
}
Btw, GridView must be visible even it's empty.
If you just want to add rows to the table for presentation, then #Mostafa Shehata answer should work fine.
However adding rows in JavaScript does not attached it to the GridView datasource. Therefore you'll experience issues with processing the data in the backend (such as saving to database).
Two possible solutions:
Replace GridView with a html table. The data can be populated & updated using a JavaScript calls to a restful API.
Pre-populate the GridView datasource with empty rows.
Data-bind x amount of empty fields (for example 10 empty fields).
In the GridView markup hide all the rows using css.
Run JavaScript to show rows that are not empty.
The “add row” button can just show the first empty row.
Add some sort of notification, if all empty fields have been used. (for example: "please save your data, before continuing").
In code behind, remove all empty fields before consuming it.

Display DataGrid Column as Hyperlink Column depending on column value

I have the below DataGrid which works with no problem
<asp:DataGrid ID="fileBrowserGrid" runat="server" Width="100%" PageSize="14" AllowPaging="True"
CellPadding="1" GridLines="None" BorderColor="#636E92" BorderWidth="0px" AutoGenerateColumns="False"
OnPageIndexChanged="fileBrowserGrid_PageIndexChanged">
<AlternatingItemStyle CssClass="mainbodytextalt"></AlternatingItemStyle>
<ItemStyle CssClass="metadatabodytext"></ItemStyle>
<HeaderStyle CssClass="metadatabodytitle"></HeaderStyle>
<FooterStyle CssClass="Blue"></FooterStyle>
<Columns>
<asp:BoundColumn DataField="LoadedFileID" HeaderText="Loaded File Id" Visible="False"></asp:BoundColumn>
<asp:BoundColumn DataField="DataSupplierCode" HeaderText="Data Supplier Code"></asp:BoundColumn>
<asp:BoundColumn DataField="DataSupplierName" HeaderText="Data Supplier Name"></asp:BoundColumn>
<asp:BoundColumn DataField="Filename" HeaderText="File Name"></asp:BoundColumn>
<asp:BoundColumn DataField="DateLoaded" HeaderText="Date Loaded"></asp:BoundColumn>
<asp:BoundColumn DataField="LoadStatus" HeaderText="Status"></asp:BoundColumn>
</Columns>
<PagerStyle CssClass="Gray"></PagerStyle>
</asp:DataGrid>
code behind:
DataSet dataSet = results.DataSet;
this.fileBrowserGrid.DataSource = dataSet;
this.fileBrowserGrid.DataBind();
I want to change the Status column so that will display a hyperlink to errormessage.aspx with id as querystring value if the value is 'Failed' but stay as normal text value if its anything else.
Ideally I don't want to make changes to my stored procedures
I've been looking at RowDataBind but haven't been able to get that working.
Any ideas? Thank you!
I have a solution with only the aspx and not touch the cs backend
You can predict the render of template Column. Try this
I suppose that the code status that indicate failed is "failed"
<asp:TemplateColumn>
<HeaderTemplate>
<b>Status </b>
</HeaderTemplate>
<ItemTemplate>
<asp:PlaceHolder ID="Ok" runat="server" Visible='<%# (Eval("LoadStatus").ToString()=="Failed"?false:true) %>'><%----%>
<asp:Label ID="Label1" Text='<%# Eval("LoadStatus") %>' runat="server" />
</asp:PlaceHolder>
<asp:PlaceHolder ID="Ko" runat="server" Visible='<%# (Eval("LoadStatus").ToString()=="Failed"?true:false) %>'><%----%>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%# string.Format("DataLoaderErrorMessage.aspx?id={0}",Eval("LoadedFileID"))%>'><%# Eval("LoadStatus") %></asp:HyperLink>
</asp:PlaceHolder>
</ItemTemplate>
</asp:TemplateColumn>
1) Set the AutoGenerateColumns property of the datagrid to false.
2) Create a template column instead of a bound column for the status.
3) Set the 'DataField' property for every column (Except the template column) so they know which value to display from the sql datasource.
4) Edit the template column and add a html div in there with the id divStatus
<asp:TemplateField HeaderText="Status">
<ItemTemplate>
<div id="divStatus" runat="server">
</div>
</ItemTemplate>
</asp:TemplateField>
Iterate through all the rows after setting the datasource of the gridview and do something like the following.
for(int i = 0; i < dataSet.Tables[0].Rows.Count; i++)
{
HtmlGenericControl divStatus = (HtmlGenericControl)fileBrowserGrid.Rows[i].FindControl("divStatus");
if(dataSet.Tables[0].Rows[i]["LoadStatus"].ToString() != "Failed")
divStatus.InnerHtml = dataSet.Tables[0].Rows[i]["LoadStatus"].ToString();
else
divStatus.InnerHtml = "<a href='pageURL.aspx?ID=" + dataSet.Tables[0].Rows[i]["LoadedFileID"].ToString() + "'> Failed : " + dataSet.Tables[0].Rows[i]["LoadedFileID"].ToString() + "</a>";
}

Read gridview cell values and text

I am using the below code to read gridview controls value or text. But it return null value. I can't find out. But the gridview having some record with the value. Please help me to solve this.
GridViewRow row = null;
for (int i = 0; i < grd.Rows.Count; i++)
{
row = grd.Rows[i];
HiddenField file_id = (HiddenField)row.FindControl("FLD_ID");
Label pack_name = (Label)row.FindControl("FLD_NAME");
string text = file_id.Value;
bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;
if (isChecked)
{
//Here its comming
}
}
My partial gridview code here
<asp:GridView ID="grd" runat="server" BackColor="#CCCCCC" BorderColor="#93afba"
BorderStyle="Solid" BorderWidth="1px" CellPadding="4" AllowPaging="True" AutoGenerateColumns="False"
ShowHeaderWhenEmpty="True" PageSize="50" Width="100%" CellSpacing="2" ForeColor="#93afba"
Font-Size="14px">
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<%--<asp:CheckBox ID="chkall" runat="server" OnChange="checkAll();" />--%>
<input id="Checkbox2" type="checkbox" onclick="CheckAll(this)" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
<ItemStyle Width="20px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="FLD_ID" Visible="false">
<ItemTemplate>
<asp:HiddenField ID="lbl_id" runat="server" Value='<%#Bind("FLD_ID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="NAME">
<ItemTemplate>
<asp:Label ID="lbl_packname" runat="server" Text='<%#Bind("FLD_NAME") %>' ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
i think you want to find Checkbox2 and you are finding chkSelect
please replace this
bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;
with
bool isChecked = ((System.Web.UI.HtmlControls.HtmlInputCheckBox)grd_proforma_bill.HeaderRow.FindControl("Checkbox2")).Checked;
your code is fine.
if you are binding gridview on page load be sure your code is as below block
if (!IsPostBack)
{
//code to bind gridview
}
Change the code to and check:
for (int i = 0; i < grd_proforma_bill.Rows.Count; i++)
{
HiddenField file_id = (HiddenField)grd_proforma_bill.Rows[i].FindControl("lbl_id");
Label pack_name = (Label)grd_proforma_bill.Rows[i].FindControl("lbl_packname");
string text = file_id.Value;
CheckBox cb = (CheckBox)grd_proforma_bill.Rows[i].FindControl("Checkbox2");
bool isChecked = cb.Checked;
if (isChecked)
{
//Here its comming
}
}

Categories