When I run my ExportTextFile method The data from my middle Credit File column is missing. I am thinking this is because it is an itemTemplate field but I need it to stay that way so I can hide a portion on that column when the gridview is displayed. So when I open the exported text file It only shows the column headers and the first column AppID and third column CreationDate. Is there a way to fix this?
relevant code
protected void ExportTextFile (object sender, EventArgs e)
{
String strDestinationFile;
strDestinationFile = "C:\\CreditFile.txt";
TextWriter tw = new StreamWriter(strDestinationFile);
//writing the header
for (int x = 0; x < GridView4.Columns.Count; x++)
{
tw.Write(GridView4.Columns[x].HeaderText);
if (x != GridView4.Columns.Count - 1)
{
tw.Write(", ");
}
}
tw.WriteLine();
//writing the data
for (int x = 0; x < GridView4.Rows.Count - 1; x++)
{
for (int y = 0; y < GridView4.Columns.Count; y++)
{
tw.Write($"{GridView4.Rows[x].Cells[y].Text.ToString()}");
if (y != GridView4.Columns.Count - 1)
{
tw.Write(", ");
}
}
tw.WriteLine();
}
tw.Close();
}
<asp:GridView ID="GridView4" runat="server" AutoGenerateColumns="False" BackColor="White" BorderColor="#E7E7FF" BorderStyle="None" BorderWidth="1px" CellPadding="3" DataKeyNames="AppID,ServiceRequestID,ServiceRequestCreditFileID" DataSourceID="SqlDataSource2" GridLines="Horizontal">
<AlternatingRowStyle BackColor="#F7F7F7" />
<Columns>
<asp:BoundField DataField="AppID" HeaderText="AppID" ReadOnly="True" SortExpression="AppID">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
<asp:TemplateField HeaderText="Credit File" SortExpression="CreditFile">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("CreditFile") %>'></asp:TextBox>
</ItemTemplate>
<ItemTemplate>
<div style="width: 100px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap;">
<asp:Label ID="Label1" runat="server" Text='<%# Bind("CreditFile") %>'></asp:Label>
</div>
</ItemTemplate>
<ItemStyle HorizontalAlign="Left" Wrap="True" />
</asp:TemplateField>
<asp:BoundField DataField="CreationDate" DataFormatString="{0:d}" HeaderText="CreationDate" SortExpression="CreationDate">
<ItemStyle HorizontalAlign="Left" />
</asp:BoundField>
</Columns>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
<SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<SortedAscendingCellStyle BackColor="#F4F4FD" />
<SortedAscendingHeaderStyle BackColor="#5A4C9D" />
<SortedDescendingCellStyle BackColor="#D8D8F0" />
<SortedDescendingHeaderStyle BackColor="#3E3277" />
</asp:GridView>
Instead of exporting the data from the grid, can you build the export off of the data source that you used to bind the grid with instead?
Otherwise, if you are using a templated column with control in it, you have to get the control from the cell and then retrieve the value from the control, something like this:
(TextBox)GridView4.Rows[x].FindControl("TextBox1").Text;
Related
What I need to do is to highlight each row when it is processing to show the process progress, the gridview may contain almost one thousands of row. below is the code I have written but which doesn't work.
Please can someone help me.
<
asp:GridView ID="gdview1" runat="server" BackColor="White"
BorderColor="#DEDFDE" BorderStyle="Solid" BorderWidth="1px" CellPadding="4"
ForeColor="Black" GridLines="Vertical" Font-Names="Calibri"
Font-Size="Small" AutoGenerateColumns="False"
OnRowDataBound="gdview1_RowDataBound"
OnSelectedIndexChanged="gdview1_SelectedIndexChanged">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkBxHeader" OnCheckedChanged="chkSelect_CheckedChanged" AutoPostBack="true" runat="server" />
</HeaderTemplate>
<EditItemTemplate>
<asp:CheckBox ID="chkNUM" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkNUM" runat="server" DataField="ColNUM" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Row#">
<ItemTemplate>
<%# Container.DataItemIndex + 1 %>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ColNUM" HeaderText="Contract #" />
<asp:BoundField DataField="Col1" HeaderText="Suffix" />
<asp:BoundField DataField="Col2" HeaderText="First Name" />
<asp:BoundField DataField="Col3" HeaderText="Last Name" />
<asp:BoundField DataField="Col4" HeaderText="Street" />
<asp:BoundField DataField="Col5" HeaderText="City" />
<asp:BoundField DataField="Col6" HeaderText="Zip" />
</Columns>
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
namespace WebApplication1
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void butChargeCreditCards_Click(object sender, EventArgs e)
{
DataTable tblContrts = (DataTable) Session["tblContrts"];
foreach (GridViewRow row in gdview1.Rows)
{
CheckBox chkbx = (CheckBox) row.FindControl("chkNUM");
if (chkbx != null && chkbx.Checked)
{
gdview1_SelectedIndexChanged(row,e);
string SS = chkbx.Text.ToString();
string strResults = method1;
}
}
}
protected void gdview1_SelectedIndexChanged(object sender, EventArgs e)
{
foreach (GridViewRow row in gdview1.Rows)
{
if (row.RowIndex == gdview1.SelectedIndex)
{
row.BackColor = ColorTranslator.FromHtml("#A1DCF2");
}
else
{
row.BackColor = ColorTranslator.FromHtml("#FFFFFF");
}
}
}
}
}
Have you tried it by using the "OnRowDataBound" or "OnRowCreated" Event of the Grid and write the color-highliting in code behind?
Something like this?
http://www.java2s.com/Code/ASP/ADO.net-Database/UsingtheRowCreatedEventtoprogrammaticallychangethestyle.htm
But maybe you have a problem because the loading would be too fast to really notice?
I would like to manually add rows to a GridView, and display it at Page Load. For some reason, my current code shows an empty GridView.
Default.aspx
<asp:GridView ID="AllocationGridView" runat="server" ShowHeaderWhenEmpty="true" AutoGenerateColumns="False"
Width="691px" CellPadding="4" ForeColor="#333333" GridLines="None" AllowSorting="True"
AutoPostBack="true">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" Height="2px" />
<Columns>
<asp:TemplateField HeaderText="Asset Class">
<ItemStyle Font-Size="13px" Width="20%" />
<ItemTemplate>
<asp:Label ID="AssetLabel" runat="server" ReadOnly="true" Text="" BorderWidth="0px"
Style="text-align: left;"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Weight">
<ItemStyle Font-Size="13px" Width="20%" />
<ItemTemplate>
<asp:TextBox ID="WeightTextBox" runat="server" ReadOnly="true" BorderWidth="0px"
Style="text-align: left;"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#EBEBEB" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" Height="10px" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
Default.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
FirstAllocationGridViewRow();
}
}
protected void FirstAllocationGridViewRow()
{
DataTable table = new DataTable();
string[] assets = new string[] { "Cash", "US Equity", "Fixed Income", "BAS", "International" };
table.Columns.Add(new DataColumn("Col1", typeof(string)));
table.Columns.Add(new DataColumn("Col2", typeof(double)));
DataRow dr = table.NewRow();
for (int i = 0; i < assets.Count(); i++)
{
dr = table.NewRow();
dr["Col1"] = assets[i];
dr["Col2"] = DBNull.Value;
table.Rows.Add(dr);
}
ViewState["currentAllocationTable"] = table;
AllocationGridView.Visible = true;
AllocationGridView.DataSource = table;
AllocationGridView.DataBind();
}
your cs code is fine the problem is in your layout code. text property is not bind to table field name
Text='<%# Bind("Col1") %>'
here is the complete gridview
<asp:GridView ID="AllocationGridView" runat="server" ShowHeaderWhenEmpty="true" AutoGenerateColumns="False"
Width="691px" CellPadding="4" ForeColor="#333333" GridLines="None" AllowSorting="True"
AutoPostBack="true">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" Height="2px" />
<Columns>
<asp:TemplateField HeaderText="Asset Class">
<ItemStyle Font-Size="13px" Width="20%" />
<ItemTemplate>
<asp:Label ID="AssetLabel" runat="server" ReadOnly="true" Text='<%# Bind("Col1") %>' BorderWidth="0px"
Style="text-align: left;"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Weight">
<ItemStyle Font-Size="13px" Width="20%" />
<ItemTemplate>
<asp:TextBox ID="WeightTextBox" runat="server" Text='<%# Bind("Col2") %>' ReadOnly="true" BorderWidth="0px"
Style="text-align: left;"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#EBEBEB" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" Height="10px" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
Remove the AutoPostBack="true" field in Gridview control. And make sure the Data-table have correct values for the columns and please see Text="" in your gridview labels . You need give values for the labels.
See this link , It's may helps you
Your problem is with your Template Fields as you cannot set values to them using a DataTable, change them to BoundFields or set AutoGenerateColumns="True"
Tried your code with my answer, it worked fine.
I have a gridview control on my web form with 1 template field column.
And i am adding some bounded columns at run time from code behind.
And some times I've removed some of the previously added columns from code behind.
After removing any column gridview losses template column.
What is the cause behind this and how can i prevent template column with out setting EnableViewState="false".
Edit-1
.aspx page Code
<asp:GridView ID="grvSum" runat="server" Width="100%" GridLines="None" AllowPaging="True" ShowFooter="true"
PageSize="25" CellPadding="4" ForeColor="#333333" AutoGenerateColumns="false" AllowSorting="true" EnableViewState="false"
OnRowUpdating="grvSum_RowUpdating" OnPageIndexChanging="grvSum_PageIndexChanging" OnSorting="grvSum_Sorting"
OnRowDataBound="grvSum_RowDataBound" Font-Size="10px">
<Columns>
<asp:TemplateField >
<ItemTemplate>
<asp:LinkButton ID="dtype" runat="server" CommandName="update"
CssClass="lbl" Font-Underline="true" style="cursor:pointer;" Text="Details" >
</asp:LinkButton>
</ItemTemplate>
<ItemStyle Width="20px"/>
<FooterTemplate>
<asp:Label ID="lblFooter" runat="server" Text="Total"></asp:Label>
</FooterTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle BackColor="White" HorizontalAlign="Center"/>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" HorizontalAlign="Center"/>
<HeaderStyle HorizontalAlign="Center" BackColor="#507CD1" Font-Bold="True" ForeColor="White" Height="30px" Wrap="true"/>
<PagerStyle HorizontalAlign="Right" CssClass="GridPager" />
<RowStyle BackColor="#EFF3FB" HorizontalAlign="Center"/>
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" CssClass="headerSortUp" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" CssClass="headerSortDown"/>
</asp:GridView>
Code for adding and removal of column
public void AddBoundedColumns(GridView grv, DataColumnCollection dtDataSourceColumns)
{
var gridBoundColumns = grv.Columns.OfType<BoundField>();
foreach (DataColumn col in dtDataSourceColumns)
{
//Check existence of column in gridview
if (gridBoundColumns.Any(bf => bf.DataField.Equals(col.ColumnName)) == false)
{
//Declare the bound field and allocate memory for the bound field.
BoundField bfield = new BoundField();
//Initalize the DataField value.
bfield.DataField = col.ColumnName;
//Initialize the HeaderText field value.
bfield.HeaderText = col.ColumnName;
bfield.SortExpression = col.ColumnName;
//Add the newly created bound field to the GridView.
grv.Columns.Add(bfield);
}
}
gridBoundColumns = grv.Columns.OfType<BoundField>();
int z = 0;
for (int x = 0; x < gridBoundColumns.Count(); x++)
{
BoundField c = gridBoundColumns.ElementAt(z);
if (!dtDataSourceColumns.Contains(c.HeaderText))
{
grv.Columns.Remove(c);
}
else
{
z++;
}
}
}
instead of grv.Columns.Remove(c);, try following while removing the column
grv.columns.RemoveAt(index); //"index" is the index of column you want to remove
SQL Server table structure:
ChapName varchar(200)
Status varchar(1)
Requirement:
I want to display checkbox in an ASP.NET gridview from Visual Studio 2010
if the value of status column is T, let it be checked and unchecked otherwise.
but it shows only textbox.
I have tried <asp:templatefield> and <asp:itemtemplate> but it throws error if I try to bind this checkbox.
any sample code is required as I am beginner in this field.
The code I tried:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
CheckBox c = (CheckBox)GridView1.FindControl("ChkStatus");
TextBox TB = (TextBox)GridView1.FindControl("Status");
//Response.Write(TB.Text);
if (TB.Text == "T")
{
c.Checked = true;
}
else
{
c.Checked = false;
}
}
The error I got
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web
request. Please review the stack trace for more information about the
error and where it originated in the code.
Exception Details:
System.NullReferenceException: Object reference not set to an instance
of an object.
Aspx markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="Comp,QTypeCode" DataSourceID="SDS_QType_Edit"
BackColor="White" BorderColor="#DEDFDE" BorderStyle="None"
BorderWidth="1px"
CellPadding="4" ForeColor="Black" GridLines="Vertical"
AllowPaging="True" AllowSorting="True"
onselectedindexchanged="GridView1_SelectedIndexChanged"
onrowdatabound="GridView1_RowDataBound">
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:CommandField ShowEditButton="True" ShowSelectButton="True" />
<asp:BoundField DataField="QTypeCode" HeaderText="QTypeCode"
SortExpression="QTypeCode" InsertVisible="False"
ReadOnly="True" />
<asp:BoundField DataField="Descr" HeaderText="Descr" SortExpression="Descr" />
<asp:CheckBoxField DataField="AnsReq" HeaderText="AnsReq" ReadOnly="True"
SortExpression="AnsReq" />
<asp:CheckBoxField DataField="OptionPrint" HeaderText="OptionPrint"
ReadOnly="True" SortExpression="OptionPrint" />
<asp:BoundField DataField="Status" HeaderText="Status"
SortExpression="Status" />
<asp:BoundField DataField="TransDate" HeaderText="TransDate"
SortExpression="TransDate" />
<asp:BoundField DataField="UserName" HeaderText="UserName"
SortExpression="UserName" />
<asp:TemplateField HeaderText="Check Box" >
<ItemTemplate>
<asp:CheckBox ID ="ChkStatus" Text="text" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle Wrap="False" />
<EmptyDataRowStyle Wrap="False" />
<FooterStyle BackColor="#CCCC99" />
<HeaderStyle Wrap="False" BackColor="#6B696B" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#F7F7DE" ForeColor="Black" HorizontalAlign="Right" />
<RowStyle Wrap="False" BackColor="#F7F7DE" />
<SelectedRowStyle BackColor="#CE5D5A" Font-Bold="True" ForeColor="White"
Wrap="False" />
<SortedAscendingCellStyle BackColor="#FBFBF2" />
<SortedAscendingHeaderStyle BackColor="#848384" />
<SortedDescendingCellStyle BackColor="#EAEAD3" />
<SortedDescendingHeaderStyle BackColor="#575357" />
</asp:GridView>
Assume you have grid defined as below on asmx
<asp:GridView ID="GridView1" runat="server"
onrowdatabound="GridView1_RowDataBound" AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ChapName" HeaderText="ChapName" />
<asp:TemplateField HeaderText="Status" Visible ="false">
<ItemTemplate>
<asp:Label ID="Status" runat="server" Text='<%# Bind("Status") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Check Box" >
<ItemTemplate>
<asp:CheckBox ID ="ChkStatus" Text="text" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
on Row Data Bound event you can find controls as below
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
CheckBox c = e.Row.FindControl("ChkStatus") as CheckBox;
Label lbl = e.Row.FindControl("Status") as Label;
if (c!= null && lbl != null )
{
c.Checked = (lbl.Text == "T");
}
}
I have a GridView that is built from a Linq query as follows
var GridViewLoad = from d in QVuser.QlikViewDashboards.AsEnumerable()
join p in tempPermissions.AsEnumerable() on d.DashboardId equals Convert.ToInt32(p["DashboardId"])
where Convert.ToInt32(p["UserId"]) == GridViewUser
select new
{
DashboardId = d.DashboardId,
PermissionId = Convert.ToInt32(p["PermissionId"]),
DashboardName = d.DashboardName,
Operational_Unit = p["Operational_Unit"].ToString(),
Cost_Centre = p["Cost_Centre"].ToString(),
Project = p["Project"].ToString(),
Fund = p["Fund"].ToString()
};
GridView1.DataSource = GridViewLoad;
GridView1.DataKeyNames = new string[] {"PermissionId"};
GridView1.DataBind();
Then the GridView is defined as:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="3"
GridLines="Vertical" ShowHeaderWhenEmpty="True" OnRowDeleting="GridView1_RowDeleting"
style="text-align: center" BackColor="White" BorderColor="#999999"
BorderStyle="None" BorderWidth="1px" Width="550px"
>
<AlternatingRowStyle BackColor="#DCDCDC" />
<Columns>
<asp:TemplateField HeaderText="Delete" ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="DeleteButton" runat="server" CausesValidation="false"
CommandArgument='<%# Eval("PermissionId") %>' CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="PermissionId" HeaderText="ID"/>
<asp:BoundField DataField="DashboardName" HeaderText="Dashboard" ReadOnly="True" SortExpression="DashboardName" />
<asp:BoundField DataField="Operational_Unit" HeaderText="Operational_Unit" ReadOnly="True" SortExpression="Operational_Unit" />
<asp:BoundField DataField="Cost_Centre" HeaderText="Cost_Centre" ReadOnly="True" SortExpression="Cost_Centre" />
<asp:BoundField DataField="Fund" HeaderText="Fund" ReadOnly="True" SortExpression="Fund" />
<asp:BoundField DataField="Project" HeaderText="Project" ReadOnly="True" SortExpression="Project" />
</Columns>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" BorderStyle="Solid" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" BorderStyle="Solid"
BorderWidth="1px" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
What I want to do is hide the PermissionId field from sight, but it obviously still needs to be there for the Delete button to work..
Can someone help me out with this?
I've tried setting Visible="false", which hides it, but then my delete button stops working..
Cheers for your help..
Since you're setting the DataKeyNames, you should be able to retrieve the permission ID from the index of the row being deleted, like so:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int permissionId = (int)GridView1.DataKeys[e.RowIndex].Value;
DoDelete(permissionId);
}
This should work whether the column is visible or not.
Try
<asp:BoundField DataField="PermissionId" HeaderText="ID" Visible="False"/>