Populating a GridView from a DataTable - c#

I am new ASP.NET and I have never used a GridView or DataGrid, but I cannot find helpful examples online on how to do what I need. I need some data to be displayed on a page and I know that I should use a GridView, but I cannot seem to get anything to display.
I have the following DataSet:
DataSet ds = new DataSet("MyTables");
ds.Tables.Add("Users");
ds.Tables["Users"].Columns.Add("ID");
ds.Tables["Users"].Columns.Add("Name");
ds.Tables["Users"].Columns.Add("Email");
ds.Tables["Users"].Rows.Add(0,"Ace","ace#example.com");
ds.Tables["Users"].Rows.Add(1,"Biff","biff#example.com");
ds.Tables["Users"].Rows.Add(2,"Chuck","chuck#example.com");
ds.Tables["Users"].Rows.Add(3,"Dick","dick#example.com");
myGrid.DataSource = ds.Tables["Users"].DefaultView;
myGrid.DataBind();
Heres is my ASP.NET:
<asp:GridView ID="myGrid" runat="server">
</asp:GridView>

I think you're adding columns to the wrong table. Try something like this:
DataSet ds = new DataSet("MyTables");
ds.Tables.Add("Users");
DataTable userTable = ds.Tables["Users"];
userTable.Columns.Add("ID");
userTable.Columns.Add("Name");
userTable.Columns.Add("Email");
userTable.Rows.Add(0,"Ace","ace#example.com)";
userTable.Rows.Add(1,"Biff","biff#example.com)";
userTable.Rows.Add(2,"Chuck","chuck#example.com)";
userTable.Rows.Add(2,"Dick","dick#example.com)";
myGrid.DataSource = userTable;
myGrid.DataBind();

I'm thinking that you're getting a object null reference error. What's happening is that you're creating columns in a table called 'add users' where there is no table called 'add users'. If you just change the three lines that you have ds.Tables["Add Users"] and change that to just ds.Tables["Users"] everything should work out just fine.
Hope this works for you.

You are referencing two completely different tables. You create the Table USERS then add columns to a table called ADD USERS then add rows to the Users table. Nothing will show up when you bind this.
Change this code
ds.Tables["Add Users"].Columns.Add("ID");
ds.Tables["Add Users"].Columns.Add("Name");
ds.Tables["Add Users"].Columns.Add("Email");
to this
ds.Tables["Users"].Columns.Add("ID");
ds.Tables["Users"].Columns.Add("Name");
ds.Tables["Users"].Columns.Add("Email");

Related

ASP.NET GridView set with DataSet, can't edit rows

I'm having the following problem:
What I have is a search function that runs a query on my database using a SqlDataAdapter.
I then use:
DataSet ds = new DataSet();
dataAdapter.Fill(ds, "table title");
gridView1.DataSource = ds;
gridView1.DataBind();
I originally got an error that I then had both a dataSource and dataSourceId, so I cleared the previously used ID. The code works, I can search the table and my query will return rows and update the table. The problem is that I want the data that it returns to be editable. I have my grid view editable, and before I run the query, I can edit the rows of the table. But after the search is run, and the gridView is filled with my DataSet, I'm unable to update the rows. If I click the edit button, it gives me an error saying the RowEditing event wasn't handled.
I looked into that event, and understand what's happening, if I were to program in the events for RowEditing/RowUpdating/RowUpdated etc. I could get it to work, but is there no better way to do this? Is there a simpler way to set my dataSource in C# and be able to maintain the editablity of the rows?
Thanks a lot!
I suppose part of the question would be would you want to? I guess you're looking for a SaveDataChanges() method which brings about a few design concerns. One is you have to remember that web pages are stateless so to an extent your web page post isn't aware of the data it's just pulled and bound to the UI. The grid view control in a round about way nicely gets the user to help you out here and click update on the row they've amended. With this you have your event handler and you can just focus on the data that's been changed and just send one UPDATE statement.

get header of a selected gridview column

I'm making a simple web application in C#. The site which I'm working on contains a GridView. The GridView shows the data from an Oracle SQL data table.
Now I want to have filtering options for my table. But I want to make it very easy to switch through the columns and I want to make it possible to filter and maybe sort each column for itself.
I already made a TextBox which instantly filters a specific column. But I want to have the User to select the column. My idea is to have the user selecting a column and then he only has to write his criteria into the TextBox.
My main problem at the moment is to figure out how to make the user able to select a column and get its index/header-text.
For instance: I want to get the index/header-text if the user wants to filter/sort the column and somehow selected it.
I'm new on asp.net and I don't really know how to realize this. I've searched a lot to find any solutions, but there isn't much about this.
I used this for my filtering method (works):
dt = GridView1.DataSource as DataTable;
dt.DefaultView.RowFilter = string.Format("Name LIKE '%{0}%'", textBox1.Text);
GridView1.DataSource = dt;
GridView1.DataBind();
For sort by column specify inside the tag of the Gridview:
AllowSorting="true">
</asp:gridview>
For Getting the header text of any column:
Gridview.Columns[i].HeaderText
No possible to filter by columns with a checkbox on the header

ASP.NET: Programatically DataBind a GridView control

I have a blank/unbound GridView control on my form and I am binding it in the code behind like this:
GridView1.DataSource = _dataSet
DataBind()
Running this code populates my GridView control with all the columns and data that _dataSet has. I want to display only some of the columns, change the column names, and rearrange some of these columns too (i want the last column from the actual sql database table to be displayed first in my GridView).
Can someone show me how do do this?
Set the AutoGenerateColumns property of the GridView to false and manually create the columns. That would be the easiest way.
Another way is to also set AutoGenerateColums property to false but this time, append the colums to the columns property of the GridView. Use the .Clear and the Add methods provided
First of all, in your GridView markup, you can change the header text:
<asp:BoundField DataField="SOME_COLUMN" HeaderText="Comment" SortExpression="SOME_COLUMN" />
Be sure to set AutoGenerateColumns to false.
Second of all, you can filter using DataSource.FilterExpression = "col1 = 'this'", if your dataset is being populated by a SqlDataSource or similar.
I've written an article that focuses on different ways to create columns in a GridView. It also discusses how to change the name of a column etc. I hope it will be of use to those, who are new to the GridView: http://www.tomot.de/en-us/article/7/asp.net/gridview-overview-of-different-ways-to-bind-data-to-columns

adding columns and mid binding a dataset for gridview etc

not sure of what to put as the title here, but basically I am using subsonic in asp.net forms C# and I have an instance where I need to loop through a recordset and for each one call the Database to get specific information from a view about that record.
in this instance it is a venue, loop through and for each venue I show there spend and there budget, but I am at a loss as to how I can say use a gridview, execute more code on each row and then add more columns to that row.
many thanks for all advise
:-)
just as an update i have been playing with the idea of something like this:
DataSet ds = new DataSet();
ds.Tables.Add(LinqToDataTable(club.All().Where(x => x.level == 1)));
ds.Tables.Add(LinqToDataTable(ViewBudgetSpend.All().Where(x => x.periodfrom == curperiod)));
DataRelation relation = new DataRelation("budgets",ds.Tables[0].Columns["clubId"],ds.Tables[1].Columns["clubid"]);
ds.Relations.Add(relation);
still working this out though.
That is a good idea, but even better, just make one big table, not a relation. GridView works better that way, with a flat tabular data source, so you are essentially denormalizing the results into one table and binding. This works great as you can manipulate the table by adding columns, then looping through the rows and updating with your new values.
Alternatively, you can work after the fact, by using the GridView RowDataBound, and manually passing data to controls in a TemplateField column.
HTH,
Brian

how to clear gridview

I want to clear my gridview. I have 2 GridViews and Has Select Button On It. on Selecting this button that item goes into the second gridview. now the question is how should i clear the second grid view. I am trying the clear method but clear method is not found in my visual studio..
dataGridView1.DataSource = null;
or
dataGridView1.Rows.Clear();
gridview.DataSource = null;
//rebind to gridview
gridview.DataBind();
Bind the Gridview to an empty list.
Binding it to 'null' like Patrick Kafka mentioned should work - unless you have some column requirements (I'm mentioning it because I have a tendancy to plug in javascript into my gridviews and unless you specify those columns in the markup, they won't be generated and it will cause errors in the js. (This is also relevant to those getting errors after doing Columns.Clear )
In a case like that (as well as in all other cases), you can simply bind the gridview to a new instance (or empty instance) of your datasource. (Below example for a gridview bound to a datatable - it could be bound to new List<T>() as well).
grdiview1.DataSource = new DataTable();
grdiview1.DataBind();
dataGridView1.Columns.Clear(); //this clears the entire Gridview
Simply add the following c# code to clear the GridView:-
gridView.Rows.Clear();

Categories

Resources