how to initialize multiple objects at once in c# - c#

I need to initialize multiple objects like this.
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
DataTable dt3 = new DataTable();
DataTable dt4 = new DataTable();
Is there a way to initialize them as
DataTable dt1, dt2, dt3, dt4 = new DataTable();
If I use above, there are no compile errors but there are runtime errors says An Object reference not set to an instance.
How can I achieve this.

No, thereĀ“s no such way, you have to initialize them one by one.
Your error appears because dt1 to dt3 are initialized to null, only dt4 has a value. Thus doing anything with d1 will throw a NullReferenceException.
But you can do so in a single line:
DataTable t1 = new DataTable(), t2 = new DataTable(), t3 = new DataTable(), t4 = new DataTable();
Even better would be a list/array:
var tables = new[] { new DataTable(), new DataTdable(), new DataTable(), new DataTable() };
or even
var tables = Enumerable.Range(0, 4).Select(x => new DataTable());

Related

Display multiple data table in DataGrid View in winForms

I have faced a problem that I have a set of data tables in a dataset.I want to show them in a DataGrid view but It can only show one datatable.Is there any way to show more that one data table in a grid view?I mean more than one without any relation defined among tables.
Here is how I have added my data to a dataset
DataSet ds = new DataSet();
DataTable RunoffEnergy = new DataTable();
RunoffEnergy.Columns.Add("RF");
RunoffEnergy.Columns.Add("LD");
RunoffEnergy.Columns.Add("DT");
RunoffEnergy.Columns.Add("K(DT)");
RunoffEnergy.Columns.Add("K(LD)");
RunoffEnergy.Columns.Add("KE");
RunoffEnergy.Rows.Add();
RunoffEnergy.Rows[0][0] = this.RF.ToString();
RunoffEnergy.Rows[0][1] = this.Ld.ToString();
RunoffEnergy.Rows[0][2] = this.Dt.ToString();
RunoffEnergy.Rows[0][3] = this.K_Dt.ToString();
RunoffEnergy.Rows[0][4] = this.K_Ld.ToString();
RunoffEnergy.Rows[0][5] = this.Ke.ToString();
//
DataTable EstimationOfRunoff = new DataTable();
EstimationOfRunoff.Columns.Add("Rc");
EstimationOfRunoff.Columns.Add("Qe");
EstimationOfRunoff.Columns.Add("Q");
EstimationOfRunoff.Rows.Add();
EstimationOfRunoff.Rows[0][0] = this.Rc.ToString();
EstimationOfRunoff.Rows[0][1] = this.Qe.ToString();
EstimationOfRunoff.Rows[0][2] = this.Q.ToString();
//
DataTable DetachmentOfSoilParticles = new DataTable();
DetachmentOfSoilParticles.Columns.Add("Fc", typeof(double));
DetachmentOfSoilParticles.Columns.Add("Fs");
DetachmentOfSoilParticles.Columns.Add("Fz");
DetachmentOfSoilParticles.Columns.Add("F", typeof(double));
DetachmentOfSoilParticles.Columns.Add("Hc");
DetachmentOfSoilParticles.Columns.Add("Hz");
DetachmentOfSoilParticles.Columns.Add("Hs", typeof(double));
DetachmentOfSoilParticles.Columns.Add("H");
DetachmentOfSoilParticles.Rows.Add();
DetachmentOfSoilParticles.Rows[0][0] = this.Fc;
DetachmentOfSoilParticles.Rows[0][1] = this.Fs.ToString();
DetachmentOfSoilParticles.Rows[0][2] = this.Fz.ToString();
DetachmentOfSoilParticles.Rows[0][2] = this.F.ToString();
DetachmentOfSoilParticles.Rows[0][2] = this.Hc.ToString();
DetachmentOfSoilParticles.Rows[0][2] = this.Hs.ToString();
DetachmentOfSoilParticles.Rows[0][2] = this.Hz.ToString();
DetachmentOfSoilParticles.Rows[0][2] = this.H.ToString();
//
DataTable ImidiateDepositionOfSoil = new DataTable();
ImidiateDepositionOfSoil.Columns.Add("Nfc", typeof(double));
ImidiateDepositionOfSoil.Columns.Add("Nfs");
ImidiateDepositionOfSoil.Columns.Add("Nfz");
ImidiateDepositionOfSoil.Columns.Add("DEPc", typeof(double));
ImidiateDepositionOfSoil.Columns.Add("DEPs");
ImidiateDepositionOfSoil.Columns.Add("DEPz");
ImidiateDepositionOfSoil.Rows.Add();
ImidiateDepositionOfSoil.Rows[0][0] = this.Nfc;
ImidiateDepositionOfSoil.Rows[0][1] = this.Nfs.ToString();
ImidiateDepositionOfSoil.Rows[0][2] = this.Nfz.ToString();
ImidiateDepositionOfSoil.Rows[0][2] = this.DEPc.ToString();
ImidiateDepositionOfSoil.Rows[0][2] = this.DEPs.ToString();
ImidiateDepositionOfSoil.Rows[0][2] = this.DEPz.ToString();
//
DataTable DeleveryOfDetachedParticles = new DataTable();
DeleveryOfDetachedParticles.Columns.Add("Gc", typeof(double));
DeleveryOfDetachedParticles.Columns.Add("Gs");
DeleveryOfDetachedParticles.Columns.Add("Gz");
DeleveryOfDetachedParticles.Columns.Add("G", typeof(double));
DeleveryOfDetachedParticles.Rows.Add();
DeleveryOfDetachedParticles.Rows[0][0] = this.Gc;
DeleveryOfDetachedParticles.Rows[0][1] = this.Gs.ToString();
DeleveryOfDetachedParticles.Rows[0][2] = this.Gz.ToString();
DeleveryOfDetachedParticles.Rows[0][2] = this.G.ToString();
//
DataTable TransportCapesity = new DataTable();
TransportCapesity.Columns.Add("Tc", typeof(double));
TransportCapesity.Columns.Add("Ts");
TransportCapesity.Columns.Add("Tz");
TransportCapesity.Columns.Add("T", typeof(double));
TransportCapesity.Rows.Add();
TransportCapesity.Rows[0][0] = this.Tc;
TransportCapesity.Rows[0][1] = this.Ts.ToString();
TransportCapesity.Rows[0][2] = this.Tz.ToString();
TransportCapesity.Rows[0][2] = this.T.ToString();
//
ds.Tables.Add(DeleveryOfDetachedParticles);
ds.Tables.Add(EstimationOfRunoff);
ds.Tables.Add(DetachmentOfSoilParticles);
ds.Tables.Add(ImidiateDepositionOfSoil);
// ds.Tables.Add(DeleveryOfDetachedParticles);
ds.Tables.Add(TransportCapesity);
these data does not have any relations.they are just the results of some calculations
If it is not possible how Can I display these data in a user friendly way?
Thank you so much
One option: Perform Join operation on these tables in Linq, Store result into a data table;then assign this new datatable as datasource of grid.
this might be helpfull to join data tables in linq -LINQ join two DataTables

Object reference not set to an instance of an object when I try to join 2 DataTables

I'm trying to join 2 DataTables but I' m getting this error:
Object reference not set to an instance of an object
this is what I'm doing:
DataTable NodeDataTable = new DataTable();
DataTable sdosDataTable = new DataTable();
private DataTable NodedataTable()
{
XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("stuff.xml"));
DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
if (ds.Tables.Count != 0)
{
NodeDataTable = ds.Tables[22];
}
return NodeDataTable;
}
private DataTable SdosDataTable()
{
XmlTextReader xmlreader = new XmlTextReader(Server.MapPath("stuff.xml"));
DataSet ds = new DataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
if (ds.Tables.Count != 0)
{
sdosDataTable = ds.Tables[10];
}
return sdosDataTable;
}
and to join both DataTables:
private void JoinNodeSdosDT()
{
DataColumn obj_NodeID, obj_SdosID;
DataSet ds1 = new DataSet();
NodeDataTable = NodeDataTable.Copy();
sdosDataTable = sdosDataTable.Copy();
ds1.Tables.Add(NodeDataTable);
ds1.Tables.Add(sdosDataTable);
obj_NodeID = ds1.Tables["node"].Columns["node_Id"];
obj_SdosID = ds1.Tables["sdos"].Columns["node_Id"];
sdosDataTable.Columns.Add("typeCodee");
DataRelation obj_NodeandSdosRelation = new DataRelation("dept_reln", obj_NodeID, obj_SdosID);
ds1.Relations.Add(obj_NodeandSdosRelation);
foreach (DataRow dr_NodeSods in ds1.Tables["sdos"].Rows)
{
DataRow dr_NondeeeR = dr_NodeSods.GetParentRow("dept_reln");
dr_NodeSods["typeCodee"] = dr_NondeeeR["typeCode"];
}
DataTable dtResult = ds1.Tables["sdos"].DefaultView.ToTable(false, "node_Id", "typeCode", "sdos_Id");
GridView1.DataSource = dtResult;
}
there is some any matching ID what can I do here to resolve my problem.
I removed The datatable Images there is no use of them.
Looks like dr_NondeeeR is null:
DataRow dr_NondeeeR = dr_NodeSods.GetParentRow("dept_reln");
dr_NodeSods["typeCodee"] = dr_NondeeeR["typeCode"];
because for whatever reason GetParentRow is returning null.
As the documentation of DataRow.Item (String) states, accessing a non-existing column should give an ArgumentException. What you are getting is a NullReferenceException. If that happens actually in the line you gave, then I can only assume that
DataRow dr_NondeeeR = dr_NodeSods.GetParentRow("dept_reln");
gives a null reference.

How can I convert a datatable to a related dataset

I have denormalized data in a DataTable.
The data contains employee names, and the pay they got over a series of pay cycles. i.e.:
My DataTable contains:
Employee 1 Jan-1-2012 $100
Employee 2 Jan-1-2012 $300
Employee 1 Feb-1-2012 $400
Employee 2 Feb-1-2012 $200
Employee 1 Mar-1-2012 $150
Employee 2 Mar-1-2012 $325
How can load this data into a DataSet where the parent DataTable contains the employees name, and the child DataTable contains details of the paycheck?
DataSet is nothing but a collection of DataTables. So to "load" the dataTable into dataSet simple Add it:
DataTable employees = new DataTable();
DataTable payCheckes = new DataTable();
DataSet ds = new DataSet();
ds.Tables.Add(employees);
ds.Tables.Add(payCheckes);
Do you want to "combine" datatables somehow?
Get paycheckes of each employee?
the code without manual insert:
DataSet ds = new DataSet();
DataTable dtemploye = new DataTable();
DataTable dtpayment = new DataTable();
ds.Tables.AddRange(new DataTable[] { dtemploye, dtpayment });
DataColumn dcIdemploye = dtemploye.Columns["ID_EMPLOYEE"];
DataColumn dcIdemployeprice = dtpayment.Columns["ID_EMPLOYEE"];
DataRelation drrelation = new DataRelation("relemploy_payment", dcIdemploye, dcIdemployeprice);
ds.Relations.Add(drrelation);
DataSet ds = new DataSet();
DataTable dtemploye = new DataTable();
DataColumn dcnameemploye = new DataColumn();
DataColumn dcIdemploye = new DataColumn();
dtemploye.Columns.AddRange(new DataColumn[]{dcnameemploye,dcIdemploye});
DataTable dtpayment = new DataTable();
DataColumn dtprice = new DataColumn();
DataColumn dtDate = new DataColumn();
DataColumn dcIdemployeprice = new DataColumn();
dtpayment.Columns.AddRange(new DataColumn[]{dcIdemployeprice,dtprice,dtDate});
DataRow drrowemploy = dtemploye.NewRow();
drrowemploy[0] = "1";
drrowemploy[1] = "Employee 1";
dtemploye.Rows.Add(drrowemploy);
DataRow drrowpayment = dtpayment.NewRow();
drrowpayment[0] = "1";
drrowpayment[0] = "01/01/2012";
drrowpayment[1] = " 300";
ds.Tables.AddRange(new DataTable[]{dtemploye, dtpayment});
DataRelation drrelation = new DataRelation("relemploy_payment", dcIdemploye, dcIdemployeprice);
ds.Relations.Add(drrelation);

Two BindingSource objects with same DataSource property

I have some difficulties with understanding BindingSource's behaviour.
Let's look at following example:
Creating table
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(int));
dt.Rows.Add(new object[] { 0 });
dt.Rows.Add(new object[] { 1 });
dt.Rows.Add(new object[] { 2 });
dt.Rows.Add(new object[] { 3 });
Creating two BindingSource objects with same DataSource property
BindingSource bs1 = new BindingSource();
BindingSource bs2 = new BindingSource();
bs1.DataSource = dt;
bs2.DataSource = dt;
At this point I supposed, that created BindingSource are fully independent. But really it is not so. After changing Filter property of bs1:
`bs1.Filter = "id >= 2";`
Filter property of bs2 doesn't change, but RowFilter property of underlying DataView (List property of BindingSource) of both BindingSource objects is changed.
It turns out that both BindingSource objects have exactly same instance of DataView i.e. condition bs1.List == bs2.List is true.
My question is why they share same List and how one can change this behaviour?
EDIT:
I've found explanation for "why they're sharing same List?" - it seems that List is assigned from DataTable's DefaultView property (so both bs1.List == bs2.List, bs1.List == dt.DefaultView are true).
It seems that to change this behaviour one can create two different DataView instances for DataTable and assign them to DataSource property of two BindingSource objects accordingly:
BindingSource bs1 = new BindingSource();
BindingSource bs2 = new BindingSource();
bs1.DataSource = new DataView(dt);
bs2.DataSource = new DataView(dt);
I'm not yet an expert in C#, but from what I've read I understand this:
by using DataTable dt = new DataTable(); you create only one instance of that object. If that instance changes, it will change for anything that references it.
you'd need to create two instances, and set each instance of BindingSource to reference its own instance of DataTable like so:
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
bs1.DataSource = dt1;
bs2.DataSource = dt2;
Ruben's answer didn't work for me but pointed me in right direction.
I had to set filter in binding source to make it work.
Below is the code that worked for me
BindingSource bs1 = new BindingSource();
BindingSource bs2 = new BindingSource();
bs2.Filter = "My Filter"; // Instead of setting filter on DataView, I had to set it on binding source.
bs1.DataSource = new DataView(dt);
bs2.DataSource = new DataView(dt);
//bs2.DataSource = new DataView(dt, RowFilter: "My Filter", Sort: "", RowState: DataViewRowState.CurrentRows); // This does not work.

datacoloumn in asp.net

I first want to add a database column in DataColumn..and then i have to add datacoloumn in datatable.. please guide me;
SqlDataAdapter d2 = new SqlDataAdapter("select MARK_PARTA from exam_cyctstmarkdet",con);
DataColumn c = new DataColumn();
c.ColumnName = "parta";
c.DataType = System.Type.GetType("System.Int32");
Is the bit you're missing
DataTable DT = new DataTable;
d2.Fill(DT);
DT.Columns.Add(c);
???
If you wish to create a DataTable, and add your own columns to it, you can try
DataTable dt = new DataTable("MyTable");
DataColumn col = dt.Columns.Add("parta", typeof(int));
You only have to keep a reference to the column if you plan to use it somewhere, else you can try
DataTable dt = new DataTable("MyTable");
dt.Columns.Add("parta", typeof(int));
I would suggest that you use the SqlDataAdapter to populate a DataSet, which will contain a DataTable. I assume you want to add the new column to this DataTable.
Here's how to do that:
SqlDataAdapter d2 = new SqlDataAdapter("select MARK_PARTA from exam_cyctstmarkdet",con);
DataSet dst = new DataSet();
d2.Fill(dst); // now you have a populated DataSet containing a DataTable
DataTable dt = dst.Tables[0]; // I created this variable for clarity; you don't really need it
DataColumn c = new DataColumn();
c.ColumnName = "parta";
c.DataType = System.Type.GetType("System.Int32");
dt.Add(c);
After you add the Column to the DataTable, the Column will be empty.
You can populate it in code.

Categories

Resources