Monday, December 20, 2004

Data binding to a dataset from everywhere (.Net General)

Q: How can i bind data to a datagrid when the data is fully in my dataset and i need to add some data from some textboxes/myself/other datasets/other datatables for every row?

Everytime someone asks this kinda question in one of the forums, I go through the pain of typing the same thing over and over again. So I decided to write it down here and point them to here. Most of you, as usual, already know all this stuff, so I'll just do it for the sake of those who posted this question and those who are still posting...
So here is goes;

In the above described case, what I usually do is to create a datatable of my own and then fill in with all the data that i need to put in and then bind this datatable to the datagrid. It doesn't matter where the data is coming from becuase we are goin to format it in our datatable as we want.
That's it, thats the answer..
Yours truly,
R. Thomas.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
Naahh... Just kidding, I guess some people won't stop there, they will continue hunting for some related code, so here is a snippet.

First, create a datatable

Dim dt As DataTable = New System.Data.DataTable("Temp")

Then make this DataTable correlate your datagrid,

dt.Columns.Add("ItemA")
dt.Columns.Add("SNo")
dt.Columns.Add("ItemB")
dt.Columns.Add("Item1")
dt.Columns.Add("Item2")
dt.Columns.Add("Strange1")
dt.Columns.Add("Different1")

Now we add rows to this DataTable, here is where the concept takes place. You've gotta prepare the rows as you want

Dim dRow As DataRow
dRow = dt.NewRow
dRow(0) = 'Comes from your first datatable
dRow(1) = dtSes.Rows.Count + 1
dRow(2) = 'Comes from your second datatable
dRow(3) = 'Comes from somewhere else
dRow(4) = 'Comes from another dataset
dRow(5) = 'Comes from some other dataset's some table
dRow(6) = 'Comes from some place else
dt.Rows.Add(dRow)

This logic of fillin up the data will usually be in a loop where the data is pouring out from a reader or coming from looping thru a dataset. So you should take care that durin this you dont get an 'Index Out of bound' exception, by running out of data in one of the tables or somethin..
By the end of that loop the datatable created by you will be full of the data that you want. So all you have to do now is to bind this table to your datagrid.


myDataGrid.DataSource = dt
myDataGrid.DataBind()

That's it. you have a data grid with the data that you want.


Comments:
This is EXACTLY what I am looking for. You posted this in ms.public.dotnet.framework.aspnet.datagridcontrol in reply to my request which is exactly this!!

THANK YOU!!
 
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?

© Copyright 2005, Rohan Thomas
Disclaimer
This Blog contains findings that are self-explored and expressions that are self-evoked. They are by no meanss representions of my employer's view.