How can a create a DataTable programatically? - c#

How can I create a DataTable programatically? i have the following code and I was wanting to create a data table just like in Java that would allow me to create a table that I could file with data from a CSV (,) such as names, address, and phone numbers.
Code:
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private System.Data.DataSet dataSet;
System.Data.DataTable table = new DataTable("ParentTable");
public Form1()
{
InitializeComponent();
}
private void MakeParentTable()
{
DataColumn column;
DataRow row;
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "id";
column.ReadOnly = true;
column.Unique = true;
table.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "ParentItem";
column.AutoIncrement = false;
column.Caption = "ParentItem";
column.ReadOnly = false;
column.Unique = false;
table.Columns.Add(column);
DataColumn[] PrimaryKeyColumns = new DataColumn[1];
PrimaryKeyColumns[0] = table.Columns["id"];
table.PrimaryKey = PrimaryKeyColumns;
dataSet = new DataSet();
dataSet.Tables.Add(table);
for (int i = 0; i<= 2; i++)
{
row = table.NewRow();
row["id"] = i;
row["ParentItem"] = "ParentItem " + i;
table.Rows.Add(row);
}
}
private void Form1_Load(object sender, EventArgs e)
{
MakeParentTable();
}
}
}

Use FileStream and StreamReader for reading data from csv file. I see that you create DataTable programmaticaly in your code.

Related

Calculating the sum of previous rows in a column in a DataTable

I'm having some trouble calculating the sum of all previous rows in a column in a data structure like DataTable
For example, we have a table with columns "Waiting Time" and "Burst Time".
Waiting Time's row values must be calculated by taking the values from previous rows in the Burst Time column(if there are such a.k.a its not the first row that we are calculating values for currently)
How can I achieve that? Is it as simple as using Compute() and passing an appropriate filter string?
EDIT: An example of what I want to do.
I have made an example. Have now idea how you populate DataTable, that is why I came up with hardcoded one.
public class Program
{
public static void Main(string[] args)
{
dataSet = new DataSet();
var dataTable = MakeTable();
var columns = dataTable.Columns;
Console.WriteLine("Defined Table");
PrintDataTable(dataTable);
foreach (DataRow dataTableRow in dataTable.Rows)
{
var id = dataTableRow["ID"];
var burstTime = dataTable.Compute("Sum(BurstTime)", $"ID < {id}");
dataTableRow["WaitingTime"] = burstTime;
}
Console.WriteLine();
Console.WriteLine("Table After Operation");
PrintDataTable(dataTable);
Console.ReadLine();
}
private static void PrintDataTable(DataTable dataTable)
{
foreach (DataRow dataTableRow in dataTable.Rows)
{
Console.WriteLine($"{dataTableRow["Id"]}\t\t| {dataTableRow["WaitingTime"]}\t\t| {dataTableRow["BurstTime"]}");
}
}
private static DataSet dataSet;
private static DataTable MakeTable()
{
// Create a new DataTable.
DataTable table = new DataTable("childTable");
DataColumn column;
DataRow row;
// Create first column and add to the DataTable.
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "ID";
column.AutoIncrement = true;
column.Caption = "ID";
column.ReadOnly = true;
column.Unique = true;
// Add the column to the DataColumnCollection.
table.Columns.Add(column);
// Create second column.
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "ChildItem";
column.AutoIncrement = false;
column.Caption = "ChildItem";
column.ReadOnly = false;
column.Unique = false;
table.Columns.Add(column);
// Create third column.
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "ParentID";
column.AutoIncrement = false;
column.Caption = "ParentID";
column.ReadOnly = false;
column.Unique = false;
table.Columns.Add(column);
// Create third column.
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "WaitingTime";
column.AutoIncrement = false;
column.Caption = "WaitingTime";
column.ReadOnly = false;
column.Unique = false;
table.Columns.Add(column);
// Create fourth column.
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.ColumnName = "BurstTime";
column.AutoIncrement = false;
column.Caption = "BursTime";
column.ReadOnly = false;
column.Unique = false;
table.Columns.Add(column);
dataSet.Tables.Add(table);
// Create three sets of DataRow objects,
// five rows each, and add to DataTable.
for (int i = 0; i <= 4; i++)
{
row = table.NewRow();
row["ID"] = i;
row["ChildItem"] = "Item " + i;
row["ParentID"] = 0;
row["WaitingTime"] = 0;
row["BurstTime"] = i;
table.Rows.Add(row);
}
for (int i = 0; i <= 4; i++)
{
row = table.NewRow();
row["ID"] = i + 5;
row["ChildItem"] = "Item " + i;
row["ParentID"] = 1;
row["WaitingTime"] = 0;
row["BurstTime"] = i + 5;
table.Rows.Add(row);
}
for (int i = 0; i <= 4; i++)
{
row = table.NewRow();
row["ID"] = i + 10;
row["ChildItem"] = "Item " + i;
row["ParentID"] = 2;
row["WaitingTime"] = 0;
row["BurstTime"] = i + 10;
table.Rows.Add(row);
}
return table;
}
}
The most interesting for you, I suppose:
foreach (DataRow dataTableRow in dataTable.Rows)
{
var id = dataTableRow["ID"];
var burstTime = dataTable.Compute("Sum(BurstTime)", $"ID < {id}");
dataTableRow["WaitingTime"] = burstTime;
}
The most important here, I think, is that you have to come up with your own comparison logic, i.e. the second parameter in Compute(string, string) function.

How do i read a row from a datatable in C#?

I'm looking for a simple way to read a row from a data table. I'm sure this has been answered somewhere but for the life of me i cant find it.
my code is as follows:
static void Main(string[] args)
{
DataTable table1 = new DataTable("myTable");
DataColumn column;
DataRow row;
table1.PrimaryKey = new DataColumn[] { table1.Columns["idnum"] };
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.AutoIncrement = false;
column.ColumnName = "name";
column.ReadOnly = true;
column.Unique = false;
table1.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.AutoIncrement = false;
column.ColumnName = "type";
column.ReadOnly = true;
column.Unique = false;
table1.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.AutoIncrement = false;
column.ColumnName = "atk";
column.ReadOnly = true;
column.Unique = false;
table1.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.Int32");
column.AutoIncrement = false;
column.ColumnName = "spd";
column.ReadOnly = true;
column.Unique = false;
table1.Columns.Add(column);
row = table1.NewRow();
row["name"] = "long sword";
row["type"] = "weapon";
row["atk"] = 7;
row["spd"] = 4;
table1.Rows.Add(row);
row = table1.NewRow();
row["name"] = "short sword";
row["type"] = "weapon";
row["atk"] = 5;
row["spd"] = 5;
table1.Rows.Add(row);
row = table1.NewRow();
row["name"] = "dagger";
row["type"] = "weapon";
row["atk"] = 3;
row["spd"] = 8;
table1.Rows.Add(row);
foreach(DataRow rowly in table1.Rows)
{
//what goes here?
}
Console.ReadKey();
}
what do i write to see the data in the row?
You can print those values by using the following code:
int rowIndex=0;
StringBuilder rowValueBuilder = new StringBuilder();
foreach (DataRow rowly in table1.Rows)
{
rowValueBuilder.AppendFormat("Row {0} Values \n", rowIndex++);
rowValueBuilder.AppendFormat("Name : {0} \n", rowly["name"]);
rowValueBuilder.AppendFormat("Type : {0} \n", rowly["type"]);
rowValueBuilder.AppendFormat("Atk : {0} \n", rowly["atk"].ToString());
rowValueBuilder.AppendFormat("Spd : {0} \n", rowly["spd"].ToString());
}
Console.WriteLine(rowValueBuilder.ToString());

Losing data and gridview C#

I have a program by VC2008 that send dataTable I sended it using the constractor I solve it help at losing data entered in dataview C# - to datagridview in another Form it work fine but I want to send only the new row I tried to copy using ImportRrow it to another datatable but it gives Form2 Blank.
and I send the data as datatable by method as following:
public DataTable showout2()
{
DataTable dtab = new DataTable();
DataColumn dc1 = new DataColumn("رقم المتسلسل");
DataColumn dc2 = new DataColumn("رقم الحساب");
DataColumn dc3 = new DataColumn("أسم الحساب");
DataColumn dc4 = new DataColumn("المالك");
DataColumn dc5 = new DataColumn("قيمة");
DataColumn dc6 = new DataColumn("نوع العملة");
DataColumn dc7 = new DataColumn("الدائن");
DataColumn dc8= new DataColumn("المدين");
DataColumn dc9= new DataColumn("تاريخ");
DataColumn dc10 = new DataColumn("تفاصيل");
dtab.Columns.Add(dc1);
dtab.Columns.Add(dc2);
dtab.Columns.Add(dc3);
dtab.Columns.Add(dc4);
dtab.Columns.Add(dc5);
dtab.Columns.Add(dc6);
dtab.Columns.Add(dc7);
dtab.Columns.Add(dc8);
dtab.Columns.Add(dc9);
dtab.Columns.Add(dc10);
DateTime date = new DateTime();
date = DateTime.Now;
// Create an array for the values.
object[] newRow = new object[10];
Set the values of the array.
string s = numb.Text;
newRow[0] = numb.Text;
newRow[1] = Account_numb.Text;
newRow[2] = Account_nam.Text;
newRow[3] = owner.Text;
newRow[4] = curency.Text;
newRow[5] = comboBox1.Text;
newRow[6] = Depet.Text;
newRow[7] = cridet.Text;
newRow[8] = date.ToString();
newRow[9] = note.Text;
declare DataRow and adding it to DataTable
DataRow row;
dtab.BeginLoadData();
// Add the new row to the rows collection.
row = dtab.LoadDataRow(newRow, true);
return dtab;
}
I transfer the data from Form as following
cashagree fm = cashagree(shouwout2());
I copy the datarow in constractor take datatable as prameter as following:
public Cashagree(DataTable d2)
{
dt.ImportRow(d2.Rows[0]);
}
here I assign the datasource and mange the secound datagridview
private void Cashagree_Load_1(object sender, EventArgs e)
{
try
{
for (int i = 0; i != dt.Rows.Count; i++){
label1.Text= dt.Rows[i].ToString();
if (string.IsNullOrEmpty(dt.Rows[i].ToString()))
{
MessageBox.Show("This is empty");
}
}
dataGridView.DataSource = dt;
dataGridView.Columns[3].Visible = false;
dataGridView.Columns[4].Visible = false;
dataGridView.Columns[5].Visible = false;
dataGridView.Columns[6].Visible = false;
dataGridView.Columns[7].Visible = false;
}
catch (Exception w) { MessageBox.Show("Error" + w.StackTrace); }
}
thank you for helping

Cannot see Decimal Value of a Cell in DataGridview C#

I cannot Display the value of "Price" cell on my gridview, here's my code:
DataColumn idCol2 = new DataColumn();
idCol2.DataType = System.Type.GetType("System.Int32");
idCol2.ColumnName = "Id";
table.Columns.Add(idCol2);
DataColumn SKUCol2 = new DataColumn();
SKUCol2.DataType = System.Type.GetType("System.String");
SKUCol2.ColumnName = "SKU";
table.Columns.Add(SKUCol2);
DataColumn ProdNameCol2 = new DataColumn();
ProdNameCol2.DataType = System.Type.GetType("System.String");
ProdNameCol2.ColumnName = "Product Name";
table.Columns.Add(ProdNameCol2);
DataColumn DescCol2 = new DataColumn();
DescCol2.DataType = System.Type.GetType("System.String");
DescCol2.ColumnName = "Product Description";
table.Columns.Add(DescCol2);
DataColumn PriceCol2 = new DataColumn();
PriceCol2.DataType = System.Type.GetType("System.Decimal");
PriceCol2.ColumnName = "Price";
table.Columns.Add(PriceCol2);
DataColumn[] keys2 = new DataColumn[5];
keys2[0] = idCol2;
table.PrimaryKey = keys2;
LivePOS livepos = new LivePOS(clientId, clientSecret);
_products = livepos.GetProducts(apiKey, token);
foreach (var p in _products)
{
table.Rows.Add(p.Id, p.Sku, p.Name, p.Description , p.SellingPrice);
}
table.DefaultView.Sort = "Id ASC";
dataGridView1.DataSource = table;
this.dataGridView1.DefaultCellStyle.Format = "N4";
foreach (DataGridViewRow row in dataGridView1.Rows)
{
row.Cells[0].ReadOnly = false; //id
row.Cells[1].ReadOnly = true; //sku
row.Cells[2].ReadOnly = true; //name
row.Cells[3].ReadOnly = true; //description
}
Please help me :)Is there something wrong in this code? I created new instance of the datatable named "table" on my Form_Load event. All cell values are displaying correctly aside from this "Price" column.
Your Price Column should have Datatype of Double than Decimal.Take a look at this link
Decimal Vs Double
hope that helps

Data Table Not Binding to Grid View

I am creating a data table and trying to bind it wit a grid view.
Code:
DataTable timeTable = new DataTable();
DataColumn colSubject = new DataColumn("Subject Name");
DataColumn colClass = new DataColumn("Class");
DataColumn colTeacher = new DataColumn("Lecturer");
DataColumn colStartTime = new DataColumn("Start");
DataColumn colEndTime = new DataColumn("End");
colSubject.DataType = System.Type.GetType("System.String");
colClass.DataType = System.Type.GetType("System.String");
colTeacher.DataType = System.Type.GetType("System.String");
colStartTime.DataType = System.Type.GetType("System.String");
colEndTime.DataType = System.Type.GetType("System.String");
timeTable.Columns.Add(colSubject);
timeTable.Columns.Add(colClass);
timeTable.Columns.Add(colTeacher);
timeTable.Columns.Add(colStartTime);
timeTable.Columns.Add(colEndTime);
int numOfRows = 0;
SqlDataReader read = null;
try
{
conn.Open();
read = getTimetable.ExecuteReader();
if (read.HasRows)
{
while (read.Read())
{
if (numOfRows < 3)
{
DataRow row = timeTable.NewRow();
row[colSubject] = read["subject_name"].ToString();
row[colClass] = read["resource_name_number"].ToString();
row[colTeacher] = read["userDetail_name"].ToString();
row[colStartTime] = read["timeSlot_startTime"].ToString();
row[colEndTime] = read["timeSlot_endTime"].ToString();
timeTable.Rows.Add(row);
numOfRows++;
}
}
gridTimeTable.DataSource = timeTable;
gridTimeTable.DataBind();
}
}
Now The Data table is Created Fine and all cause I used a breakpoint to see whether it was being created the thing is it is not populating the grid view. any ideas?
Thanks :)

Categories

Resources