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
Related
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;
i have a gridview as:
<asp:GridView ID="gdvOpinions" runat="server" Width="100%" CellPadding="4"
ForeColor="#333333" GridLines="None" Height="100px" Visible="False"
AutoGenerateColumns="False" onrowcommand="gdvOpinions_RowCommand" >
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:ButtonField ButtonType="Button" CommandName="Confirm" Text="تائید" />
<asp:ButtonField ButtonType="Button" CommandName="Delete" Text="حذف" />
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="مقاله" HeaderText="مقاله" >
<ControlStyle Width="150px" />
</asp:BoundField>
<asp:BoundField DataField="نظر کاربر" HeaderText="نظر کاربر" >
<ControlStyle Width="250px" />
</asp:BoundField>
</Columns>
<EditRowStyle BackColor="#999999" />
<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" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" />
</asp:GridView>
As you see, i have two buttonfield for every row, but when i click one of these buttons and want to get their row in
gdvOpinions_RowCommand
the
gdvOpinions.SelectedRow
returns null;
how should i find which row is selected?
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false"
OnRowCommand = "OnRowCommand">
<Columns>
<asp:ButtonField CommandName = "ButtonField" DataTextField = "CustomerID"
ButtonType = "Button"/>
</Columns>
</asp:GridView>
protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = GridView1.Rows[index];
}
From what I understand out of your question, if you are trying to get the row for which the button was clicked, then in that case this might be the right thing to do :
GridViewRow gRow = (GridViewRow)((Control)e.CommandSource).NamingContainer;
Now here, this is for a control such as a Button or ImageButton. You might have to improvise on this for ButtonField.
You can also change the ButtonField to a simple TemplateField with a Button.
Hope this helps.
I am trying to dynamically set width of gridview columns but when I apply the following code, I see no change in the browser.
.aspx code is:
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" PageSize="5" CellSpacing="4" AutoGenerateDeleteButton="True" AutoGenerateEditButton="True" CellPadding="4" DataKeyNames="File_Name" GridLines="None" OnRowEditing="GridView1_RowEditing" OnRowDeleting="GridView1_RowDeleting" OnRowUpdated="GridView1_RowUpdated" OnRowUpdating="GridView1_RowUpdating" ForeColor="#333333" OnRowCancelingEdit="GridView1_RowCancelingEdit" OnPageIndexChanging="GridView1_PageIndexChanging" AllowSorting="True" OnSorting="GridView1_Sorting" OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_OnRowDataBound">
<PagerSettings Mode="NumericFirstLast" FirstPageText="First" LastPageText="Last" PageButtonCount="10" Position="Bottom" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField HeaderText="File">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnFileName" runat="server" CommandArgument='<%# Eval("File_Name") %>' CommandName="Download" Text='<%# Eval("File_Name") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EditRowStyle BackColor="#2461BF" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#EFF3FB" />
<SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
.cs code is:
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
//SET WIDTH OF THE COLUMNS
if (e.Row.RowType == DataControlRowType.Header)
{
e.Row.Cells[0].Width = 100; //DATE
e.Row.Cells[1].Width = 100; //CUSTOMER
e.Row.Cells[2].Width = 100; //DESTINATION
}
}
Can anyone notice where I might be going wrong?
Please check .. I think you may need to do the following way
e.Row.Cells[0].Width = Unit.Pixel(500);
e.Row.Cells[1].Width = Unit.Pixel(500);
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 want to create a grid view with one column containing empty textboxes where the user can input a number (quantity), some regular columns and a column dedicated to images.
I have the following code in C#:
Label_Error.Visible = false;
DataTable dt = new DataTable();
dt.Columns.Add("Quantity", typeof(TextBox));
dt.Columns.Add("Book ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Author", typeof(string));
dt.Columns.Add("Description", typeof(string));
dt.Columns.Add("Price", typeof(float));
dt.Columns.Add("Currency", typeof(string));
dt.Columns.Add("Image", typeof(string));
DataRow row1 = dt.NewRow();
row1["Quantity"] = new TextBox();
row1["Book ID"] = 1;
row1["Name"] = "Moby Dick";
row1["Author"] = "Herman Melville";
row1["Description"] = "Adventure Book";
row1["Price"] = 10;
row1["Currency"] = "EUR";
row1["Image"] = ResolveUrl("~/Images/Logo.png");
dt.Rows.Add(row1);
GridView_Products.DataSource = dt;
GridView_Products.DataBind();
This is what I am getting at the output:
As you can see, the quantity column of empty textboxes is not being shown and the image is not being shown neither. How can I solve these two problems please?
Update
This is the code in the .aspx page:
<asp:GridView ID="GridView_Products" runat="server" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3"
HorizontalAlign="Center">
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White"
HorizontalAlign="Center" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:GridView>
You need to create column by yourself instead of auto generating them.
Here is an example -
<asp:GridView ID="GridView_Products" runat="server" BackColor="White"
BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3"
HorizontalAlign="Center" AutoGenerateColumns="False">
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White"
HorizontalAlign="Center" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
<Columns>
<asp:BoundField DataField="Book ID" HeaderText="Book ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Author" HeaderText="Author" />
<asp:BoundField DataField="Description" HeaderText="Description" />
<asp:BoundField DataField="Price" HeaderText="Price" />
<asp:BoundField DataField="Currency" HeaderText="Currency" />
<asp:TemplateField HeaderText="Quantity">
<ItemTemplate>
<asp:TextBox ID="QantityTextBox" runat="server" Text='<%# Eval("Quantity") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Image") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
DataTable dt = new DataTable();
dt.Columns.Add("Quantity", typeof(int)); // Make sure this is integer
dt.Columns.Add("Book ID", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Author", typeof(string));
dt.Columns.Add("Description", typeof(string));
dt.Columns.Add("Price", typeof(float));
dt.Columns.Add("Currency", typeof(string));
dt.Columns.Add("Image", typeof(string));
DataRow row1 = dt.NewRow();
row1["Quantity"] = 1;
row1["Book ID"] = 1;
row1["Name"] = "Moby Dick";
row1["Author"] = "Herman Melville";
row1["Description"] = "Adventure Book";
row1["Price"] = 10;
row1["Currency"] = "EUR";
row1["Image"] = "~/Images/Logo.png";
dt.Rows.Add(row1);
GridView_Products.DataSource = dt;
GridView_Products.DataBind();
Here are more about GridView column types.
Not knowing the requested specs, I would suggest using an EditItemTemplate on your GridView and placing a textbox control inside that.
Do you have to programatically create your gridview? How about this...
<asp:gridview>
<columns>
<asp:TemplateField HeaderText="...">
<ItemTemplate>
<asp:Label ID="lbl_Quantity" runat="server" Text='<%# Eval("PutDateFieldNameHere") %>'
</asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Textbox ID="txt_Quantity" runat="server" Text='<%# Eval("DataFieldName") %>'></asp:Textbox>
</EditItemTemplate>
</asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn_Edit" runat="server" CommandName="EditQty" Text="Edit" CommandArgument='<%# ("ItemId") %>' />
</ItemTemplate>
</columns>
</asp:gridview>
This design requires a button to show the textbox, but there are other ways to implement this. If you go with the button approach make sure you wire up a CommandName event in your code behind and that the primary key for each item quantity you are changing is bound to the button.