I have tried to create a data table in C#, but I want to achieve similar results to these shown in this screenshot:
I can create dynamic columns but can not create rows.
DataTable dt_bq = new DataTable();
dt_bq.Columns.Add("Date", typeof(string));
dt_bq.Columns.Add("12/8", typeof(string));
dt_bq.Columns.Add("13/8", typeof(string));
dt_bq.Columns.Add("Total", typeof(string));
DataRow dr_tot = dt_bq.NewRow();
https://learn.microsoft.com/en-us/dotnet/api/system.data.datatable?view=netframework-4.8
// Setting up header of table
DataTable dt_bq = new DataTable();
dt_bq.Columns.Add("Date", typeof(string));
dt_bq.Columns.Add("12/8", typeof(string));
dt_bq.Columns.Add("13/8", typeof(string));
dt_bq.Columns.Add("14/8", typeof(string));
dt_bq.Columns.Add("Total", typeof(string));
// Insert rows for that table
DataRow dr_tot = dt_bq.NewRow();
dr_tot["Date"] = "Issue Qty";
dr_tot["12/8"] = "10";
dr_tot["13/8"] = "20";
dr_tot["14/8"] = "30";
dr_tot["Total"] = "60";
dt_bq.Rows.Add(dr_tot);
dr_tot = dt_bq.NewRow();
dr_tot["Date"] = "Retrun Qty";
dr_tot["12/8"] = "5";
dr_tot["13/8"] = "20";
dr_tot["14/8"] = "30";
dr_tot["Total"] = "55";
dt_bq.Rows.Add(dr_tot);
dr_tot = dt_bq.NewRow();
dr_tot["Date"] = "Balance";
dr_tot["12/8"] = "5";
dr_tot["13/8"] = "0";
dr_tot["14/8"] = "0";
dr_tot["Total"] = "5";
dt_bq.Rows.Add(dr_tot);
You can add rows with column's name as index to the row. Then insert that row to the table.
Related
Captured all the required value in a Datatable.
Columns and corresponding values are added in a datatable.
**Need to pass the datatable value to the mail task in ssis package.
As it is in a table format** Please suggest
In mail values will be like this enter image description here
DataTable dt = new DataTable();
DataRow row;
DataColumn column;
column = new DataColumn();
dt.Columns.Add("Count_File_Date", typeof(String));
dt.Columns.Add("Count_File_Name", typeof(String));
dt.Columns.Add("Count_File_LMD", typeof(String));
dt.Columns.Add("Switch_File_Name", typeof(String));
dt.Columns.Add("Switch_File_Date", typeof(String));
dt.Columns.Add("Data_File_Name", typeof(String));
dt.Columns.Add("Data_File_LMD", typeof(String));
var directories = Directory.GetDirectories(directory);
foreach (string subdirectory in directories)
{
row = dt.NewRow();
dt.Rows.Add(row);
if (Directory.GetFiles(subdirectory, "*.count").Length == 0)
{
row["Count_File_Name"] = "Count File Not Found";
}
else
{
// Getting the values of count file
DateTime Count_L_M_D;
string Count_File_Name;
string[] Count_filePath1 = Directory.GetFiles(subdirectory, "*.count");
string Content = File.ReadAllText(#Count_filePath1[0]);
string loadedDate = DateTime.ParseExact(Content.Substring(9, 8), "yyyyMMdd",
CultureInfo.InvariantCulture).ToString("yyyy/MM/dd");
DateTime Datevalue = DateTime.Parse(loadedDate);
Count_File_Name = Path.GetFileName(Count_filePath1[0]);
Count_L_M_D = Directory.GetLastWriteTime(Count_filePath1[0]);
row["Count_File_Date"] = Datevalue;
row["Count_File_Name"] = Count_File_Name;
row["Count_File_LMD"] = Count_L_M_D;
}
if (Directory.GetFiles(subdirectory, "*.switch").Length == 0)
{
row["Switch_File_Name"] = "Switch File Not Found";
}
else
{
string[] Switch_filePath = Directory.GetFiles(subdirectory, "*.switch");
DateTime Switch_L_M_D;
string S_File_Name;
S_File_Name = Path.GetFileName(Switch_filePath[0]);
Switch_L_M_D = Directory.GetLastWriteTime(Switch_filePath[0]);
row["Switch_File_Name"] = S_File_Name;
row["Switch_File_Date"] = Switch_L_M_D;
}
}
I need to append rows one by one. The below code only adds the current rows and how can I add rows on top of the existing ones?
DataTable dt = new .DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Property", typeof(string));
DataRow row = dt.NewRow();
foreach (Object form in Obj)
{
string str1 = "hi";
string str2 = "hey";
row["Name"] = str1;
row["Property"] = str2;
dt.Rows.Add(row);
}
Really appreciate any suggestions?
Update 1:
My actual code
System.Data.DataTable dt = new System.Data.DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Property", typeof(string));
if (crobj.SourceName.StartsWith("{#"))
{
foreach (CRObject crform in lstObj)
{
if (crform.FormulaForm == crobj.SourceName)
{
System.Data.DataRow newRow = dt.NewRow();
newRow["Name"] = "hi";
newRow["Property"] = "hey";
dt.Rows.Add(newRow);
}
}
}
You only have one row (DataRow) object which you keep re-editing. Declare a new one within the scope of the loop:
foreach (Object form in Obj)
{
DataRow row = dt.NewRow();
//...
dt.Rows.Add(row);
}
Small change:
DataTable dt = new .DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Property", typeof(string));
foreach (Object form in Obj)
{
DataRow row = dt.NewRow(); <<<------------
string str1 = "hi";
string str2 = "hey";
row["Name"] = str1;
row["Property"] = str2;
dt.Rows.Add(row);
}
By generating a new row inside the loop, it is treated as a new row instead of the same one.
EDIT: if this doesn't work, then the Obj collection is probably not containing values. Try this to test:
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Property", typeof(string));
for (int i=0; i<5; i++)
{
DataRow row = dt.NewRow();
string str1 = "hi";
string str2 = "hey";
row["Name"] = str1;
row["Property"] = str2;
dt.Rows.Add(row);
}
With this, the resulting data table contains 5 rows.
What is wrong with my code?
dataSet = new DataSet();
dataTable = dataSet.Tables.Add("Items");
dataTable.Columns.Add("Site", typeof(string));
dataTable.Columns.Add("ItemID", typeof(UInt64));
dataTable.Columns.Add("ItemName", typeof(string));
dataTable.Columns.Add("ListedPrice", typeof(decimal));
dataTable.Columns.Add("Currency", typeof(string));
dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns["ItemID"] };
string site = "mysite";
UInt64 itemId = 44322;
string itemName = "werwer";
decimal listedPrice = 345345;
string currency = "USD";
dataTable.Rows.Add(site, itemId ,itemName, listedPrice, currency);
dataGridView1.DataSource = dataSet.Tables["Items"];
When I run it, it does not enter the row to the GridView, simply adding a blank line
EDIT
I found the problem, it was because I manually created the cells in VS IDE.
How can I still work with the IDE because I want to fix the layout not by code
Try this once..
DataSet dataSet = new DataSet();
DataTable dataTable = dataSet.Tables.Add("Items");
dataTable.Columns.Add("Site", typeof(string));
dataTable.Columns.Add("ItemID", typeof(UInt64));
dataTable.Columns.Add("ItemName", typeof(string));
dataTable.Columns.Add("ListedPrice", typeof(decimal));
dataTable.Columns.Add("Currency", typeof(string));
dataTable.PrimaryKey = new DataColumn[] { dataTable.Columns["ItemID"]
dataTable.Rows.Add("mysite",44322,"werwer", 345345,"USD");
dataGridView1.DataSource = dataSet.Tables["Items"]
I have two datatables dt1 and dt2 ,where as dt1 contains of a single column "ID" and dt2 contains of a single column "NAME". My requirement is to combine both the datatables and create a new datatable (ie)
whereas as mentioned above i need to get the datas of both the datatable (dt1 & dt2 ) and need to create a new datatable.
You can do something like this
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
dt1.Columns.Add("id", typeof(Int32));
dt2.Columns.Add("Name", typeof(String));
DataRow dr = dt1.NewRow();
dr["id"] = 1;
dt1.Rows.Add(dr);
dr = dt1.NewRow();
dr["id"] = 2;
dt1.Rows.Add(dr);
dr = dt2.NewRow();
dr["name"] = "XXX";
dt2.Rows.Add(dr);
dr = dt2.NewRow();
dr["name"] = "YYY";
dt2.Rows.Add(dr);
DataTable dt3 = new DataTable();
dt3.Columns.Add("id", typeof(Int32));
dt3.Columns.Add("Name", typeof(String));
for (int i = 0; i < dt1.Rows.Count; i++)
{
dr = dt3.NewRow();
dr["id"] = dt1.Rows[i]["id"];
dr["name"] = dt2.Rows[i]["name"];
dt3.Rows.Add(dr);
}
IF you want to combine to DataTables, you can do the following:
DataTable table1 = new DataTable("Items");
DataColumn column1 = new DataColumn("id", typeof(System.Int32));
table1.Columns.Add(column1);
DataTable table2 = new DataTable("details");
DataColumn column = new DataColumn("Name", typeof(System.String));
table1.Columns.Add(column);
table1.Merge(table2); //table1 will have 2 columns after executing this line
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();
}