GridView Column Width Altering - asp.net

Can someone please help me with my problem?
I have a gridview in a webpage, whose datasource is an oracle database. I would like to know if it is possible to change the column widths while you are on the web page?
string select = "SELECT * FROM TABLE"
OracleCommand cmd = new OracleCommand(select, connectionstring);
cmd.Connection.Open();
GridView.DataSource = cmd.ExecuteReader();
GridView.DataBind();
This outputs the table in the gridview. Is there a way to change gridview properties while in the browser? perhaps some javascript?
Thank you in advance,

You can specify these attributes through the styles in the columns of the gridview itself. You can set the AutoGenerateColumns attribute to false, and specify the columns you want, and specify the sizes within each column. Furthermore, following good web-design practices, you can use css to style each column. If you would like to change it on the fly, I would suggest using ItemTemplates, and adding components you can modify in the field.
Ex:
<asp:GridView runat="server" AutoGenerateColumns="false" ID="Grid" DataSourceID='MyObjectDataSource' CssClass="grid_table">
<AlternatingRowStyle CssClass="even" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<div id="NameColumn" runat="server">Name Center</div>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("LastName") %>, <%# Eval("FirstName") %>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<HeaderTemplate>
<div id="AgeColumn" runat="server">Age</div>
</HeaderTemplate>
<ItemTemplate>
<%# Eval("Age") %>
</ItemTemplate>
</asp:TemplateField>
<EmptyDataTemplate>There are no Users</EmptyDataTemplate>
</asp:GridView>
With this code you can access the column widths:
NameColumn.Width = 100;
AgeColumn.Width = 2;
However, there are many ways you can accomplish this, including getting the columns directly:
Grid.Columns[0].HeaderStyle.Width = 100;
Grid.Columns[0].ItemStyle.Width = 100;
Grid.Columns[1].HeaderStyle.Width = 2;
Grid.Columns[1].ItemStyle.Width = 2;
Or again using css:
Grid.Columns[0].HeaderStyle.CssClass = "name_column_header";
Grid.Columns[0].ItemStyle.CssClass = "name_column_data";
Grid.Columns[1].HeaderStyle.CssClass = "age_column_header";
Grid.Columns[1].ItemStyle.Width = "age_column_data";
Anyways, the world's your oyster, these are just some starting points.

Use this code in row databound event of the gridview
e.Row.Cells[8].Width = new Unit("800px");
please ensure your gridview size must be greater than the column size.

Related

Nested CheckBoxList using DataSet and Repeaters

I'm trying to wire up some CBL's using a repeater and dataset. The dataset contains 2 tables with the same schema and a (one, single) relation (in SQL land think of it as a self join).
When the control is rendered if I set my DataSource = the relationship, I am able to get the children elements to show; so I know the model is good, although misplaced (on purpose to test the model - see code below).
The problem is:
I am having difficulty getting the parent elements to show up at all
Not all parents have children, and the ones that don't still need to show up
Am I approaching this in the right frame of mind? i.e. Am I missing something fundamental? Implementation outside of CBL(plain text) works fine per this article
<asp:Repeater ID="ParentRepeater" runat="server">
<ItemTemplate>
<asp:CheckBoxList ID="ParentCBL" runat="server"
DataSource='<%# DataBinder.Eval(Container.DataItem,"Joined") %>'
DataTextField="TextProperty"
DataValueField="ValueProperty">
</asp:CheckBoxList>
<asp:Repeater ID="ChildRepeater" runat="server">
<ItemTemplate>
<asp:CheckBoxList ID="ChildCBL" runat="server"
DataSource='<%# DataBinder.Eval(Container.DataItem, "Joined") %>'
DataTextField="TextProperty"
DataValueField="ValueProperty">
</asp:CheckBoxList>
</ItemTemplate>
</asp:Repeater>
</ItemTemplate>
</asp:Repeater>
Page Load is nothing spectacular
DataSet ds = Foo.foo();
ParentRepeater.DataSource = ds.Tables["Parent"];
ParentRepeater.DataBind();
In your code you don't bind ChildRepeater
If you want just change plain text to Checkbox in according to https://support.microsoft.com/en-us/kb/306154
then you don't need to use CheckBoxList. But you should only use single checkbox inside repeater.

GridView loses column contents during PostBack

I am having an issue with the behavior of a GridView between post backs.
The real problem comes from a TemplateField I define in the markup at column[0] with a child CheckBox control. Things work fine for the first, and second search executions. However, at some point between the second execution and anything that causes a post back there after, I lose the contents of the TemplateField.
Its only the the contents of the column and not the whole column itself that gets removed. The TemplateField is present in the source and shows a formated column at position 0 of the table.
CODE:
protected void ExecuteSearch(object sender, EventArgs e)
{
if (lb_SelectedFields.Items.Count == 0) { return; } //if no selected fields
//Generates custom SQL query based on user inputs and column Selections
BuildQuery(); // sets txbSqlText.Text = to the SQL string
DataTable Table = SqlAdapter.Select(new System.Data.SqlClient.SqlCommand(txbSqlText.Text));
for (int i = gv_SearchResults.Columns.Count - 1; i > 0; i--)
{ gv_SearchResults.Columns.RemoveAt(i); } //removes all the columns except[0]
foreach (ListItem Item in lb_SelectedFields.Items) //adds all the user defined columns
{
//Column object that is able to find the column definition
Column Col = ColumnsBasedOnFocus.FindColumName(Item.Value);
if (Col.Type == "HyperLink") { gv_SearchResults.Columns.Add(CreateHyperLinkField(Col)); }
else { gv_SearchResults.Columns.Add(CreateBoundColumn(Col, true)); } //true is if the column is visable
}
gv_SearchResults.DataSource = Table;
gv_SearchResults.DataBind();
}
ASP.NET:
<asp:GridView ID="gv_SearchResults" runat="server" GridLines="None" CellSpacing="0"
CellPadding="0" AutoGenerateColumns="false" CssClass="TABLE_LIGHTBLUE" Width="100%">
<HeaderStyle CssClass="TABLE_LIGHTBLUE_HEADERROW" />
<Columns>
<asp:TemplateField ItemStyle-Width="30" ItemStyle-Wrap="false">
<HeaderTemplate>
<center>
<asp:Button ID="btn_SelectAll" runat="server" OnClick="SelectAll" Text="All" CssClass="TEXT_SMALL" />
<asp:CheckBox ID="chk_Placeholder" runat="server" Visible="false" /></center>
</HeaderTemplate>
<ItemTemplate>
<center>
<asp:CheckBox ID="chk_Select" runat="server" Visible="true" />
<asp:Label ID="lbl_AssetGID" runat="server" Visible="false" Text='<%# Bind("i_GID") %>' /></center>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Found a link that describes a similar situation.
https://connect.microsoft.com/VisualStudio/feedback/details/104994/templatefield-in-a-gridview-doesnt-have-its-viewstate-restored-when-boundfields-are-inserted#details
They describe a bug in ASP.Net code that fails to properly manage view states with template fields in dynamically generated grid views.
Basically TemplateFields can't be properly restored from ViewState, and if you modify the ASPX-declared columns programmatically, it can't create them from the declarations either.
The only solution I could get working was to create a new class deriving from TemplateField that in the constructor set the ItemTemplate to an ITemplate-derived class, which means having to define the template programmatically instead of declaratively.
You can also rebind the gridview on each postback but that's its own can of worms.

How to bind one column to gridview which is not present in database

How to bind one column to the gridview which is not present in the database?
I want to display the total unit in the last column named Total Unit but it is not present in database.
I got an argument exception:
Column 'tunit' does not belong to
table.
foreach(DataRow row in dt.Rows )
{
object[] obj=new object[2];
obj[0] = row["Transaction_Id"];
obj[1] = row["tunit"];
dtgrid.Rows.Add(obj);
}
The best solution to this problem is to implement unbound column as it is explained in the Unbound Columns topic.
if you are binding a list, you can add a property to that list and bind to the grid using eval("PropertyName")
When you prepare the select query make sure you have one more extra column with the total value you want for that particular row, then you can specify a column in the gridview as follows, make sure you specify
'AutoGenerateColumns = false;
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataSourceID="sds_datasourceName">
<Columns>
<asp:TemplateField HeaderText="Total" >
<itemtemplate>
<asp:Label ID="Total" runat="server" Text='<%# Bind("Total") %>'></asp:Label>
</itemtemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

Render the content of a TemplateField dynamically

I want to know if there is a way of dynamically render the content of a template field from a GridView.
This is how the grid looks and what I want, is to somehow get the rendered string of the label in the code behind.
<asp:GridView runat="server" ID="simpleGrid" AutoGenerateColumns="false" Visible="false">
<Columns>
<asp:TemplateField HeaderText="Templated Date">
<ItemTemplate>
<asp:Label ID="firstLabel" Text='<%# Eval("Date") %>' runat="server"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Thanks in advance,
Kali.
Well, the only way to get the content of a control is to use the RenderControl method, via something like:
StringWriter strings = new StringWriter();
HtmlTextWriter html = new HtmlTextWriter(strings);
Label label = //find the reference to the label
label.RenderControl(html);
This should push the control's markup into the html writer and easily extracted through the string writer. That's one way. Otherwise, no direct way to access its HTML except in client-side javascript.
HTH.

Spliting data in Asp.Net Gridview

I Have a set of choices(options) coming from Database(around 36 records) which I have to insert in Gridview in such a way that 18 will go one column and 18 in another. And As these are choices the columns are needs to be a check box columns. So What I did is I have created a data table with 2 columns and split the data accordingly and then bind it to the grid.But the problem is If the question list is having odd no of items count ie 37. It is adding a blank record with check box in my gridview. Your help will be appreciated...
see code below
In my Aspx.cs
DataTable dTable = new DataTable();
dTable.Columns.Add("Questionsclmn1", typeof(string));
dTable.Columns.Add("Questionsclmn2", typeof(string));
for (int item = 0; item < QuestionList.Count; item = item + 2)
{
DataRow drow = dTable.NewRow();
drow["Questionsclmn1"] = QuestionList[item].Question;
if ((item + 1) < QuestionList.Count)
drow["Questionsclmn2"] = QuestionList[item + 1].Question;
dTable.Rows.Add(drow);
}
GrdVwQuestionsList.DataSource = dTable;
GrdVwQuestionsList.DataBind();
In my Aspx file under gridview
<Columns>
<asp:TemplateField HeaderText="Please Choose the Options Below">
<ItemTemplate>
<asp:CheckBox ID="chkQuestionList1" runat="server"
Text='<%# DataBinder.Eval( Container.DataItem, "Questionsclmn1")%>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkQuestionList2" runat="server"
Text='<%# DataBinder.Eval( Container.DataItem, "Questionsclmn2")%>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
Thanks in Advance.
Regards,
Chetan
I wouldn't use a GridView for this at all. CheckboxList can lay out checkboxes in two columns automatically.
<asp:CheckboxList runat="server" RepeatLayout="Table" RepeatColumns="2" RepeatDirection="Vertical" ... />
There's also DataList that supports the same properties but lets you use a template for the content.

Resources