How to create datatable in C#? - c#

I tried create and fill a simple DataTable
Result of this code :
Order Driver
1
1
But I want to show on same row like this :
Order Driver
1 1
Where is my wrong in this code ?
public DataTable MethodName(string Param)
{
DataRow dr;
DataTable dt= new DataTable();
dt.Columns.Add("Order", Type.GetType("System.Int32"));
dt.Columns.Add("Driver", Type.GetType("System.Int32"));
if(AnotherMethod1(Param))
{ dr = dt.NewRow();
dr["Order"] = 1;
dt.Rows.Add(dr);
}
else
{ dr = dt.NewRow();
dr["Order"] = 0;
dt.Rows.Add(dr);
}
if(AnotherMethod2(Param))
{ dr = dt.NewRow();
dr["Driver"] = 1;
dt.Rows.Add(dr);
}
else
{ dr = dt.NewRow();
dr["Driver"] = 0;
dt.Rows.Add(dr);
}
return dt;
}

You're adding a row every time you set value to a different column.
Try this:
public DataTable MethodName(string Param)
{
DataTable dt = new DataTable();
dt.Columns.Add("Order", typeof(Int32));
dt.Columns.Add("Driver", typeof(Int32));
DataRow dr = dt.NewRow();
dr["Order"] = AnotherMethod1(Param) ? 1 : 0;
dr["Driver"] = AnotherMethod2(Param) ? 1 : 0;
dt.Rows.Add(dr);
return dt;
}

public DataTable MethodName(string Param)
{
DataRow dr;
DataTable dt= new DataTable();
dt.Columns.Add("Order", Type.GetType("System.Int32"));
dt.Columns.Add("Driver", Type.GetType("System.Int32"));
dr = dt.NewRow();
if(AnotherMethod1(Param))
{
dr["Order"] = 1;
}
else
{
dr["Order"] = 0;
}
if(AnotherMethod2(Param))
{
dr["Driver"] = 1;
}
else
{
dr["Driver"] = 0;
}
dt.Rows.Add(dr);
return dt;
}

Related

How to append row from one dataset to another dataset?

I want to add one row from dataset ds to dc every time. and I want to keep updating the Gridview to bigger the table. But when I try it in my code. the Gridview can only display one row according to what i input in the textbox.
public partial class TestGridview : System.Web.UI.Page
{
int count = 0;
DataSet dc = new DataSet();
protected void Page_Load(object sender, EventArgs e)
{
string text = TextBox1.Text;
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["XMLConnectionString"].ConnectionString);
// Create the command object
string str = "SELECT * FROM XML WHERE [Part_Numbber] = #textInput";
SqlCommand cmd = new SqlCommand(str, con);
cmd.Parameters.AddWithValue("textInput", text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "XML");
if (count == 0)
{
dc = ds.Clone();
count ++;
}
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
if (ds.Tables[0].Rows[i].ItemArray[0].ToString() != "NULL")
{
dc.Tables[0].ImportRow(ds.Tables[0].Rows[i]);
}
}
GridView1.DataSource = dc;
GridView1.DataBind();
}
}
You can make use of below code to append rows from 1 DT to other final DT. LikeWise
foreach (DataRow dataRow in dt2.Rows)
{
DataRow dr = dt1.NewRow();
dr[0] = Convert.ToInt32(dataRow[0]);
dr[1] = dataRow[1].ToString();
dr[2] = dataRow[2].ToString();
dt1.Rows.Add(dr);
}
foreach (DataRow dataRow in dt3.Rows)
{
DataRow dr = dt1.NewRow();
dr[0] = Convert.ToInt32(dataRow[0]);
dr[1] = dataRow[1].ToString();
dr[2] = dataRow[2].ToString();
dt1.Rows.Add(dr);
}
foreach (DataRow dataRow in dt4.Rows)
{
DataRow dr = dt1.NewRow();
dr[0] = Convert.ToInt32(dataRow[0]);
dr[1] = dataRow[1].ToString();
dr[2] = dataRow[2].ToString();
dt1.Rows.Add(dr);
}

fill grid view from textbox and dropddown list values recursively on each button click

I want to fill grid view with textbox and dropddown list values recursively on button click.Currently it is binding only once.I am new to ASP.NET.Help would be highly appreciated
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Resource");
dt.Columns.Add("available");
for (int intCnt = 0; intCnt < grd.Rows.Count - 1; intCnt++)
{
if (grd.Rows[intCnt].RowType == DataControlRowType.DataRow)
{
dr = dt.NewRow();
dr["Resource"] = grd.Rows[intCnt].Cells[0];
dr["available"] = grd.Rows[intCnt].Cells[1];
dt.Rows.Add(dr);
}
}
dr = dt.NewRow();
dr["Resource"] = ddlResource.SelectedItem.Text;
dr["available"] = txtavailable.Text;
dt.Rows.Add(dr);
grd.DataSource = dt;
grd.DataBind();
}
Please try this hope it will help
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataRow dr;
dt.Columns.Add("Resource");
dt.Columns.Add("available");
foreach(GridViewRow row in grd.Rows)
{
dr = dt.NewRow();
dr["Resource"] = row.Cells[0].Text;
dr["available"] =row.Cells[1].Text;
dt.Rows.Add(dr);
}
dr = dt.NewRow();
dr["Resource"] = ddlResource.SelectedItem.Text;
dr["available"] = txtavailable.Text;
dt.Rows.Add(dr);
grd.DataSource = dt;
grd.DataBind();
}
Use following code:
protected void btnAdd_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = defineColumn();
DataRow dr;
foreach (GridViewRow grow in grdChMedicine.Rows)
{
dr = dt.NewRow();
dr["Diagnosis"] = grow.Cells[1].Text;
dr["DiagnosisId"] = grow.Cells[2].Text;
dt.Rows.Add(dr);
}
dr = dt.NewRow();
dr["Diagnosis"] = ddldiagnosis.SelectedItem.ToString();
dr["DiagnosisId"] = ddldiagnosis.SelectedValue;
dt.Rows.Add(dr);
ViewState["ChMedicine"] = dt;
grdChMedicine.DataSource = dt;
grdChMedicine.DataBind();
}
private DataTable defineColumn()
{
DataTable dt = new DataTable();
dc = new DataColumn("Diagnosis");
dt.Columns.Add(dc);
dc = new DataColumn("DiagnosisId");
dt.Columns.Add(dc);
return dt;
}

GridView doesn't show my datasource

I have gridview "gvData" ,i need to fetch the data of my function to gridview :
(I am using c# application)
algorithm.prison obj=new prison();
gvData.DataSource= obj.TitForTat();
After run i have a empty gridview.
Here is my code:
public DataSet TitForTat()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("myt");
dt.Columns.Add(new DataColumn("iteration", typeof(int)));
dt.Columns.Add(new DataColumn("prison1", typeof(string)));
dt.Columns.Add(new DataColumn("prison2", typeof (string)));
prison[] prisons = new prison[2];
prisons[0] = new prison();
prisons[1] = new prison();
//---------------------------
DataRow dr = dt.NewRow();
prisons[0]._state = "c";
prisons[1]._state = valueOfState[rd.Next(0, 1)];
dr["iteration"] = 0;
dr["prison1"] = "c";
dr["prison2"] = prisons[1]._state;
dt.Rows.Add(dr);
//----------------------
for (int i = 1; i <= _iteration; i++)
{
prisons[0]._state = prisons[1]._state;
prisons[1]._state = valueOfState[rd.Next(0, 1)];
DataRow dr1 = dt.NewRow();
dr1["iteration"] =i;
dr1["prison1"] = prisons[0]._state;
dr1["prison2"] = prisons[1]._state;
dt.Rows.Add(dr1);
}
ds.Tables.Add(dt);
return ds;
}
If it's an ASP.NET-webforms GridView-control you need to call DataBind() after you have assigned the DataSource:
gvData.DataSource = obj.TitForTat();
gvData.DataBind();
If it's winforms you have to set the DataMember property if you use a DataSet instead of a DataTable:
gvData.DataSource = obj.TitForTat();
gvData.DataMember = "myt";
... or use a DataTable in the first place:
DataSet ds = obj.TitForTat();
if(ds.Tables.Count > 0)
gvData.DataSource = ds.Tables[0];

DataTable row filling in C#

I am trying to add row in DataTable CartDT using row[], which is a string array.
DataTable CartDT = new DataTable();
public void DataTableColumn()
{
CartDT.Columns.Add("Product_Name", typeof(string));
CartDT.Columns.Add("Product_ID", typeof(string));
CartDT.Columns.Add("ItemQTY", typeof(string));
CartDT.Columns.Add("Price", typeof(string));
CartDT.Columns.Add("TotalPrice", typeof(string));
}
protected void AddToCart(object sender, GridViewCommandEventArgs e)
{
string[] arg = e.CommandArgument.ToString().Split(';');
int index = Convert.ToInt32(arg[3]);
TextBox itemQuantity = (TextBox)GridView1.Rows[index].Cells[6].FindControl("txtQty");
string[] row = new string[5];
row[0] = arg[0]; //Product_Name
row[1] = arg[1]; //Product_ID
row[2] = itemQuantity.Text; //OrderQTY
row[3] = arg[2]; //Price
row[4]=(Double.Parse(arg[2]) * Convert.ToInt32(itemQuantity.Text)).ToString();// calculate total price
CartDT.Rows.Add(row);//Creating row in Datatable using row[] string array
GridView2.DataSource = CartDT;
GridView2.DataBind();
}
Now when I execute it, it gives the error that "Input array is longer than the number of columns in this table"
The array row[] has exactly 5 elements in it & also DataTable CartDT has also 5 columns.
Now i am not able to find exactly where i am wrong.
Please help me to find the bug.
Thanx in advance.
Instead do this
DataRow dr = CartDT.NewRow();
Then
dr[0] = arg[0];
and so on. In the end
CartDT.Rows.Add(dr);
CartDT.AcceptChanges();
This way the instance of Row will have CartDT schema.
DataTable CartDT = new DataTable();
public void CreateDataTableColumns()
{
CartDT.Columns.Add("Product_Name", typeof(string));
CartDT.Columns.Add("Product_ID", typeof(string));
CartDT.Columns.Add("ItemQTY", typeof(string));
CartDT.Columns.Add("Price", typeof(string));
CartDT.Columns.Add("TotalPrice", typeof(string));
}
protected void AddToCart(object sender, GridViewCommandEventArgs e)
{
if (CartDT.Columns.Count = 0)
{
CreateDataTableColumns();
}
string[] arg = e.CommandArgument.ToString().Split(';');
int index = Convert.ToInt32(arg[3]);
TextBox itemQuantity =
(TextBox)GridView1.Rows[index].Cells[6].FindControl("txtQty");
DataRow dr = CartDT.NewRow();
dr[0] = arg[0]; //Product_Name
dr[1] = arg[1]; //Product_ID
dr[2] = itemQuantity.Text; //OrderQTY
dr[3] = arg[2]; //Price
dr[4] = (Double.Parse(arg[2]) * Convert.ToInt32(itemQuantity.Text)).ToString(); // calculate total price
CartDT.Rows.Add(dr);
CartDT.AcceptChanges();
GridView2.DataSource = CartDT;
GridView2.DataBind();
}
Debug, and break on
CartDT.Rows.Add(row);
and see how many columns are in CartDT; I think you don't call DataTableColumn() at the right time.
Your code having to do with row insertion works just fine
DataTable CartDT = new DataTable();
CartDT.Columns.Add("Product_Name", typeof(string));
CartDT.Columns.Add("Product_ID", typeof(string));
CartDT.Columns.Add("ItemQTY", typeof(string));
CartDT.Columns.Add("Price", typeof(string));
CartDT.Columns.Add("TotalPrice", typeof(string));
string[] row = new string[5];
row[0] = "1"; //Product_Name
row[1] = "2"; //Product_ID
row[2] = "3"; //OrderQTY
row[3] = "4"; //Price
row[4] = "5";// calculate total price
CartDT.Rows.Add(row);//Creating row in Datatable using row[] string array
for (int i = 0; i < 5; i++)
{
Console.WriteLine(CartDT.Rows[0][i]);
}
Console.Read();
Try Below Code:
protected void AddToCart(object sender, GridViewCommandEventArgs e)
{
string[] arg = e.CommandArgument.ToString().Split(';');
int index = Convert.ToInt32(arg[3]);
TextBox itemQuantity = (TextBox)GridView1.Rows[index].Cells[6].FindControl("txtQty");
DataRow row = CartDT.NewRow();
row["Product_Name"] = arg[0]; //Product_Name
row["Product_ID"] = arg[1]; //Product_ID
row["OrderQTY"] = itemQuantity.Text; //OrderQTY
row["Price"] = arg[2]; //Price
row["TotalPrice"]=(Double.Parse(arg[2]) * Convert.ToInt32(itemQuantity.Text)).ToString();
CartDt.Rows.Add(row);
CartDT.AcceptChanges();
GridView2.DataSource = CartDT;
GridView2.DataBind();
}

from datatable to array، no loop

Following Code for transmission to the list box is :
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("BestSite", typeof(string));
dt.Columns.Add(dc);
for (int i = 1; i <= 10; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i.ToString() + " = stackoverflow";
dt.Rows.Add(dr);
}//EndFor
var Query = from mycolumn in dt.AsEnumerable()
where mycolumn.Field<string>("BestSite") != string.Empty
select mycolumn;
listBox1.DataSource = Query.AsDataView();
listBox1.DisplayMember = "BestSite";
Transfer to array what should be? no loop
string[] myvalue = new string[Query.AsDataView().Count];
Finally realized
Correct answer :
private string ConvertToString(DataRow dr)
{
return Convert.ToString(dr[0]);
}
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("BestSite", typeof(string));
dt.Columns.Add(dc);
for (int i = 1; i <= 10; i++)
{
DataRow dr = dt.NewRow();
dr[0] = i.ToString() + " = stackoverflow";
dt.Rows.Add(dr);
}//EndFor
//var Query = from mycolumn in dt.AsEnumerable()
// where mycolumn.Field<string>("BestSite") != string.Empty
// select mycolumn;
DataRow[] myrow = new DataRow[dt.Rows.Count];
dt.Rows.CopyTo(myrow, 0);
string[] myString = Array.ConvertAll(myrow, new Converter<DataRow, string>(ConvertToString));
foreach (string a in myString)
{
listBox1.Items.Add(a);
}
}
If I understood your question correctly...
string[] myvalue = Query.Select(i => i.Field<string>("BestSite")).ToArray();
This example assumes:
=> datatable is non zero length
=> values are "parsable" to double.
coln = "PurchasePrice";
double[] arr_val = Array.ConvertAll<DataRow, double>
(
dattbl.Select(),
delegate (DataRow rw) { return
double.Parse(rw[coln].ToString()); }
);
// ... and for example
double total = arr_val.Sum();

Categories