I have a datatable binded with gridview and I want to change the column width.
This it the code I use:
DataTable aTable = new DataTable("Words");
aTable.Columns.Add("word");
GridView1.DataSource = aTable;
DataRow a = aTable.NewRow();
a[0] = "test";
aTable.Rows.Add(a);
GridView1.DataBind();
GridView1.Columns[0].ItemStyle.Width = Unit.Pixel(200);
When the execution gets to the last line it produces an error saying that the column with index 0 is not found, howerver it is in the datatable and it is shown in the webpage.
Why doesn't the gridview see the column and is there a way around this?
The column count will always be 0 unless you explicitly define <columns> in your gridview.
You are autogenerating. So use <columns> with <asp:BoundField DataField="word" />and it will work.
I'd try placing this in the grid view's prerender event. You may be trying to do this in the wrong spot.
EDIT Try adding this before your statement:
if(GridView1.Columns.Count > 0)
//do stuff here
Related
I am getting started with a basic asp.net gridview control and I just dont seem to be able to make it visible in the web browser at all in an asp.net web application.
Here is what I have just to get myself started off. In the aspx page ...
<asp:GridView ID="myGr" runat="server" BackColor="Aqua" AutoGenerateColumns="True" Width="100%" ViewStateMode="Enabled"></asp:GridView>
In the code behind I have ...
Dim tbl As New DataTable
tbl.Columns.Add("ID", GetType(Int32))
tbl.Columns.Add("Name", GetType(String))
tbl.Columns.Add("Birthday", GetType(Date))
Dim pers As DataRow = tbl.NewRow
pers("ID") = 1
pers("Name") = "Tim"
pers("Birthday") = New Date(1973, 6, 9)
myGr.DataSource = tbl
myGr.DataBind()
Would be great if anyone could give me some basic advice on this control
You need to add the row you inserted to the datatable tbl. Because you haven't done this, the datatable is empty so the Gridview is empty too.
Like that: tbl.Rows.add(pers)
You create row but you do not add it to the table.
You have to add line like that:
tbl.Rows.Add(pers)
I am implementing a gridview to handle a single sql server database table. When I click to sort a column, it does so by capital letters first (e.g. Test, Test2, Test3, test1, test2). Is there a way to manipulate the sorting so that it would return the results as expected (e.g. Test, test1, Test2, test2, Test3)?
Try following in .aspx file:
<asp:GridView ID="grd" runat="server">
</asp:GridView>
And add below in .aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("Subject", typeof(string));
dt.Rows.Add("Test");
dt.Rows.Add("Test2");
dt.Rows.Add("Test3");
dt.Rows.Add("test1");
dt.Rows.Add("test2");
dt.CaseSensitive = true; // this will allow case sensitive sorting
dt.DefaultView.Sort = "Subject asc";
grd.DataSource = dt;
grd.DataBind();
}
For more details refer this link How to sort a DataView in a case-insensitive manner?
Please mark this answer useful if this solve your problem.
I think you have to use the Grid's Sorting event to do a custom sort:
http://www.nullskull.com/a/866/aspnet--sorting-a-gridview-bound-to-a-custom-data-object.aspx
Otherwise if you don't want to do that, just have the database return another column with all lowercase text. Then in the gridView Column, where you have the current Test, Test2,etc...display both in there, have one be a hidden label and set the sort to that column. I haven't tried this but it might work, so in that's columns ItemTemplate have both output but only show one, then sort on the hidden one.
I have a gridview that is SQL bound. In some of the columns there are bit values. When I use C# to get the values into the gridview, checkboxes are displayed. I need to extract the value of that column into text.
SqlConnection sConnection = new SqlConnection(MyConnectionString);
SqlCommand sCommand = new SqlCommand();
using (sConnection)
{
sCommand.Connection = sConnection;
sCommand.CommandText = "MyStoredProcedure";
sCommand.CommandType = CommandType.StoredProcedure;
sCommand.Connection.Open();
SqlDataReader reader = sCommand.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
gridView.DataSource = reader;
gridView.DataBind();
}
for (int i = 0; i < gridView.Rows.Count; i++)
{
ListBox1.Items.Add(gridView.Rows[i].Cells[3].Text);
}
}
}
The gridview column data type is 'bit'. I do not have access to the database or stored procedure to change anything there. I need to somehow extract the '0' or '1' value, but when I do it like above, the text is blank.
I also tried to use 'GetOrdinal'. It returned a True/False value from the database, but I could not figure out how to get the value for each item in the gridview.
if (!reader.IsDBNull(reader.GetOrdinal("MyColumn1")))
{
ListBox1.Items.Add(reader.GetOrdinal("MyColumn1").ToString());
}
General overview:
You need to be able to find the CheckBox that's generated and get the value of it's "Checked" property.
To do this, you need to be able to use the FindControl() method on the GridViewRow.
To use FindControl, the CheckBox needs a predictable name.
To get a predictable name, you need to have that column be a TemplateColumn so that you can specify the name of the CheckBox in the markup on the ASPX page.
There's a full working set of code here: http://www.codeproject.com/Articles/25056/The-RIGHT-Way-to-Use-Checkboxes-in-a-NET-Repeater
This shows the code for a Repeater, but it's the same principle and general code for any DataBound control.
The code below should work with modifications to match your DB names:
<asp:TemplateField>
<ItemTemplate >
<asp:checkbox id="MyColumnNameCheckbox" runat="server" />
</ItemTemplate>
</asp:TemplateField>
string defaultvalue = "0"; // To be used to display the value of the original bit field.
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox chkBx = (CheckBox)row.FindControl("MyColumnNameCheckbox");
if (chkBx != null && chkBx.Checked)
{
defaultvalue = "1";
}
}
I was able to figure it out. Thanks, David Stratton, for pointing me in the right direction.
I did it by assigning an id to the dynamically created control first. then did the FindControl()...
Control ctrl = GridView1.SelectedRow.Cells[4].Control[0];
ctrl.ID = "ctrl";
Boolean result = Convert.ToBoolean(((Checkbox)GridView1.Rows[0].Cells[4].FindControl("ctrl")).Checked);
TextBox1.Text = result.ToString();
This returns a value of "True" or "False"...
Thanks again.
Another way to resolve it:
bool result = (GridView1.SelectedRow.Cells[4].Control[0] as Checkbox).Checked;
TextBox1.Text = result.ToString();
it resolve the problem with less code :)
I'm having a problem with the dtaview. I'm dynamically creating new datacolumns, assigning them values, and adding them into my datatable. Before using a filter, this was fine when binding. All values appeared.
However, I have since chosen to reduce returned results by filtering (by letter), and my returned dataview doesn't seem to allow binding with the newly created data columns. I've mined into the filtered view, and can see that the values are present that I need.
I'm trying to avoid putting everything back into a table again after applying the filter. An sql query based on letter is out of the question, as the whole original table is sitting in view state.
Here are some code snippets:
--Firstly create new datacolumn
Dim ICount As System.Data.DataColumn = New System.Data.DataColumn
ICount.DataType = System.Type.GetType("System.String")
ICount.AllowDBNull = True
ICount.ColumnName = "ICount"
register.Columns.Add(ICount)
--integer value is first calculated and then put into the datatable row
row("ICount") = IntegerCount.ToString()
--filtered view is created from datatable (returned from viewstate)
Dim filteredView As New Data.DataView(pTable, FilterExpression, "Surname", Data.DataViewRowState.OriginalRows)
--view is bound
grd.DataSource = filteredView
grd.DataBind()
--Markup
<asp:TemplateField HeaderText ="ICount" SortExpression="ICount">
<ItemTemplate>
<asp:Label ID="IC" runat="server" Text='<%# Bind("ICount") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
All of the non dynamic datacolumns are fine. Mining into both the datatable and the filtered view show values are there.
Any help would be much appreciated!!!
Ok - fixed this.
The problem was that I wasn't using the dataset.
So instead of creating a new view, I should have done the following:
datTable = CType(ViewState("datTable"), System.Data.DataTable)
datSet.Tables.Add(datTable)
datView = datSet.Tables(0).DefaultView
datView.RowFilter = FilterExpression
grd.DataSource = datView
grd.DataBind()
All values are now coming through.
I am attempting to use an existing stored procedure to populate a gridview.
First, I execute the stored procedure and use a SqlAdapter to put it into a DataSet. I know this works because DataSet.Tables[0] contains my data. However, when I create a GridView and bind the data to the GridView, nothing is displayed.
Here is the code for binding the GridView:
DataSet ds = Execute_spr();
GridView testGridView = new GridView();
if (ds.Tables.Count > 0)
{
testGridView.DataSource = ds.Tables[0].AsEnumerable();
testGridView.DataBind();
}
and here is the code for my gridview in the .aspx page:
<asp:GridView ID="testGridView" runat = "server" AutoGenerateColumns = "true" />
Any idea what I might be doing incorrectly?
Edit: I have tried the ds.Tables[0] without AsEnumerable() and using .DefaultView
Why are you re-initialising the Gridview in the line
GridView testGridView = new GridView();
Create a protected member in your codebeind called "testGridView", remove the line above, and you might start to get somewhere...