How can i insert each time a diffrent row in datatable?
The data table is used in a dataGridView to write a log. I need each time to write in a diffrent line (row) in the datatable, when I can't know how many rows I need in runtime.
Another thing; the datatable is loaded from a XML file, so there might be already rows in the data table.
What can i do? (in short, I always write in the same row) in C#
EDIT:
here is the code:
From some reason, the DateGridView isonly having one row(This is a method that activated in a click of a button)
public void gridStart(string i, string b, string c)
{
DataTable dt = new DataTable();//empty table with no schema
DataColumn colContactID = new DataColumn("Date", typeof(string));
DataColumn colContactName = new DataColumn("Caller", typeof(string));
DataColumn colResult = new DataColumn("Result", typeof(string));
dt.Columns.Add(colContactID);
dt.Columns.Add(colContactName);
dt.Columns.Add(colResult);
DataRow row = dt.NewRow();
row["Date"] = i;
row["Caller"] = b;
row["Result"] = c;
dt.Rows.Add(row);
}
You should be able to Use DataTable.NewRow(). There are several samples on that MSDN page. If you have more questions please provide some sample code to your answer.
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = MyDataTable;
}
private string _fileName = "MyCache.xml";
private DataTable _myDataTable;
public DataTable MyDataTable
{
get
{
if (_myDataTable == null)
{
_myDataTable = new DataTable();
if (File.Exists(_fileName))
_myDataTable.ReadXml(_fileName);
else
InitDataTable(_myDataTable);
}
return _myDataTable;
}
}
private void InitDataTable(DataTable table)
{
table.TableName = "MyTable";
table.Columns.Add("Date", typeof(DateTime));
table.Columns.Add("Caller", typeof(string));
table.Columns.Add("Result", typeof(string));
}
// Have your add code call this method!
private void AddValue(DateTime date, string caller, string result)
{
var row = MyDataTable.NewRow();
row["Date"] = date;
row["Caller"] = caller;
row["Result"] = result;
MyDataTable.Rows.Add(row);
}
protected override void OnClosed(EventArgs e)
{
if (_myDataTable != null)
_myDataTable.WriteXml(_fileName, XmlWriteMode.WriteSchema);
base.OnClosed(e);
}
If it is bound to a data source, you need to first get the data source,
// Assuming it's a DataTable
DataTable dt = ((DataTable)myDataGridView.DataSource);
insert rows to your data source (like what your method is doing in your post), then tell the view to refresh its contents.
So maybe something like this would work:
public void gridStart()
{
DataTable dt = new DataTable();
DataColumn colContactID = new DataColumn("Date", typeof(string));
DataColumn colContactName = new DataColumn("Caller", typeof(string));
DataColumn colResult = new DataColumn("Result", typeof(string));
dt.Columns.Add(colContactID);
dt.Columns.Add(colContactName);
dt.Columns.Add(colResult);
dataGridView1.DataSource = dt;
// Call method to insert values.
}
to start up the grid, and:
public void gridInsert(string i, string b, string c)
{
DataTable dt = (DataTable)myDataGridView.DataSource;
DataRow row = dt.NewRow();
row["Date"] = i;
row["Caller"] = b;
row["Result"] = c;
dt.Rows.Add(row);
// Call another method to refresh grid view.
}
to call when you want to insert data to your DataTable.
My solution:
public partial class _Default : System.Web.UI.Page
{
DataTable tb = new DataTable();
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
DataTable dt = new DataTable("table");
dt.Columns.Add(new DataColumn("NR", Type.GetType("System.Int32")));
dt.Columns.Add(new DataColumn("Dihname", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("ing", Type.GetType("System.String")));
dt.Columns.Add(new DataColumn("Cost", Type.GetType("System.String")));
Session["ss"] = dt;
}
protected void LinkButton1_Click(object sender, EventArgs e)
{
tb = (DataTable)Session["ss"];
DataRow r1 = tb.NewRow();
r1[0] = ViewState["dishid"].ToString();
r1[1] = ViewState["dishname"];
r1[3] = Label3.Text;
tb.Rows.Add(r1);
DataList5.DataSource = tb;
DataList5.DataBind();
}
}
Related
I initially wrote the headers manually in my DataGrid and now I want to fill the DataGrid from a DataTable. I wanted to do it like this:
void fillingDataGrid()
{
DataTable dt = new DataTable();
DataColumn id = new DataColumn("id", typeof(int));
DataColumn name = new DataColumn("name", typeof(string));
DataColumn ort = new DataColumn("ort", typeof(string));
DataColumn alter = new DataColumn("alter", typeof(string));
DataColumn land = new DataColumn("land", typeof(string));
dt.Columns.Add(id);
dt.Columns.Add(name);
dt.Columns.Add(ort);
dt.Columns.Add(alter);
dt.Columns.Add(land);
DataRow firstrow = dt.NewRow();
firstrow[0] = 1;
firstrow[1] = "Peter";
firstrow[2] = "Berlin";
firstrow[3] = "18";
firstrow[4] = "Germany";
DataRow secondrow = dt.NewRow();
firstrow[0] = 2;
firstrow[1] = "Karl";
firstrow[2] = "Prag";
firstrow[3] = "12";
firstrow[4] = "Tschechien";
dt.Rows.Add(firstrow);
dt.Rows.Add(secondrow);
gridd.ItemsSource = dt.DefaultView;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this.fillingDataGrid();
}
The problem, however, is that if I do it this way, it is not output correctly because it looks like this:
Why doesn't it show me all the data, what do I have to change on my DataTable?
Change this line :
gridd.ItemsSource = dt.DefaultView;
To :
gridd.DataContext = dt.DefaultView;
I made a table that has 7 columns (id, date, type, name, expenses, income, saldo) in DataGridView. I also have datetime/combobox/texfields and a button to add corresponding data to the rows. The user should be able to add/delete rows and save their progress (to be able to come back to it). It is my understanding I have to bind DataTable to DataGridView, however, I keep getting exceptions like "ID field already exists" and the following columns (EXPENSES, INCOME, SALDO) are duplicated. Can anyone point me where I am wrong and show the right way to do it? I tried multiple approaches, but I still can't get it.
public partial class Form1 : Form
{
DataTable budgetTable = new DataTable();
public Form1()
{
InitializeComponent();
}
//adds a row to the table
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(cbbxType.Text) ||
string.IsNullOrWhiteSpace(expenseField.Text))
{
MessageBox.Show("'Type','Expence','Income' fields cannot be empty!");
}
else
DtgTable.DataSource = budgetTable;
DataColumn id = budgetTable.Columns.Add("ID", typeof(Int32));
DataColumn date = budgetTable.Columns.Add("DATE", typeof(DateTime));
DataColumn type = budgetTable.Columns.Add("TYPE", typeof(String));
DataColumn name = budgetTable.Columns.Add("NAME", typeof(String));
DataColumn exp = budgetTable.Columns.Add("EXPENSES", typeof(Int32));
DataColumn inc = budgetTable.Columns.Add("INCOME", typeof(Int32));
DataColumn sal = budgetTable.Columns.Add("SALDO", typeof(Int32));
DataRow row = budgetTable.NewRow();
row["ID"] = "01";
row["DATE"] = dateTime.Text;
row["TYPE"] = cbbxType.Text;
row["NAME"] = nameField.Text;
row["EXPENSES"] = expenseField.Text;
row["INCOME"] = incomeField.Text;
row["SALDO"] = 0;
budgetTable.Rows.Add(row);
}
So, thanks to all advices and some minor tweaking I made this snippet work the following way:
public Form1()
{
InitializeComponent();
budgetTable.Columns.Add("id", typeof(Int32));
budgetTable.Columns.Add("date", typeof(DateTime));
budgetTable.Columns.Add("type", typeof(String));
budgetTable.Columns.Add("name", typeof(String));
budgetTable.Columns.Add("expenses", typeof(Int32));
budgetTable.Columns.Add("income", typeof(Int32));
budgetTable.Columns.Add("saldo", typeof(Int32));
var date = DateTime.ParseExact("29MAR18", "ddMMMyy", CultureInfo.InvariantCulture);
DataRow row = budgetTable.NewRow();
row["id"] = "01";
row["date"] = date;
row["type"] = cbbxType.Text;
row["name"] = nameField.Text;
row["expenses"] = expenseField.Text;
row["income"] = incomeField.Text;
row["saldo"] = 0;
budgetTable.Rows.Add(row);
DtgTable.DataSource = budgetTable;
budgetTable.Rows.Clear();
}
//adds a row to the table
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(cbbxType.Text) ||
string.IsNullOrWhiteSpace(expenseField.Text))
{
MessageBox.Show("'Type','Expence','Income' fields cannot be empty!");
}
else
budgetTable.Rows.Add(null, dateTime.Text, cbbxType.Text, nameField.Text, expenseField.Text, incomeField.Text, 0);
}
I have this error c#
foreach statement cannot operate on variables of type int because int does not contain a public definition for GetEnumerator.
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = ord.GET_ORDER_DETAILS(textBox1.Text);
DataTable dt = new DataTable();
foreach(var r in dataGridView1.Rows.Count)
{
dt.Rows.Add(r.Cells[0].Value, r.Cells[1]);
}
}
You want to iterate the rows, not the count of the number of rows.
foreach(var r in dataGridView1.Rows)
{
dt.Rows.Add(r.Cells[0].Value, r.Cells[1]);
}
Remove the Count and try
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = ord.GET_ORDER_DETAILS(textBox1.Text);
DataTable dt = new DataTable();
foreach(var r in dataGridView1.Rows)
{
dt.Rows.Add(r.Cells[0].Value, r.Cells[1]);
}
}
I think you don't need to add each of rows, just:
DataTable dt = (DataTable)dataGridView1.DataSource;
If you only want 2 columns then try
var dtResult = ord.GET_ORDER_DETAILS(textBox1.Text);
dataGridView1.DataSource = dtResult;
DataTable dt = new DataTable();
dt.Columns.Add("Column1");
dt.Columns.Add("Column2");
foreach (DataRow item in dtResult.Rows)
{
dt.Rows.Add(item["Column1"], item["Column2"]);
}
I am using Visual C# 2008 to make a application that takes the data from textboxes and displays it in datagridview in another form the conforming make it entered to the database.
I send the data using dataTable with a function entered the data without any symentic error but when I call the other for the datagridview comes empty and the database comes empty. When I duplicate a primary key it gives an error stating "cannot duplicate primary key".
This is the code for the function that transfers that datatable
public DataTable showout() {
DataTable dtab = new DataTable();
DataColumn dc1 = new DataColumn("رقم المتسلسل");
DataColumn dc2 = new DataColumn("رقم الحساب");
DataColumn dc3 = new DataColumn("أسم الحساب");
dtab.Columns.Add(dc1);
dtab.Columns.Add(dc2);
dtab.Columns.Add(dc3);
// Create an array for the values.
object[] newRow = new object[3];
// Set the values of the array.
string s = numb.Text;
newRow[0] =numb.Text;
newRow[1] = textBox5.Text;
newRow[2] =note.Text;
DataRow row;
dtab.BeginLoadData();
// Add the new row to the rows collection.
row = dtab.LoadDataRow(newRow, true);
return dtab;
}
this is the code that I call the function in the other From
private void Cashagree_Load(object sender, EventArgs e) {
dataGridView1.DataSource = ch.showout();
}
the second datagrid entering function its in the same class
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.Visible = true;
dataGridView1.DataSource = showout();
entering(true);
}
and this is the entering to the database
public void entering(bool bl)
{try{
if (bl)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DateTime Date = DateTime.Today;
SqlCommand cmd = new SqlCommand("INSERT INTO Accont(Account_ID,Account_Name,Owners,Curency,Curncytype,Depet,Credet_devet,Date,Note) VALUES (#AccountID, #AccountName, #Owner, #Curncy,#Curncytype,#Depet,#Cridetdevet,#Date,#Note)");
cmd.CommandType = CommandType.Text;
cmd.Connection = connection;
cmd.Parameters.AddWithValue("#AccountID",numb.Text);
cmd.Parameters.AddWithValue("#AccountName", comboBox1.SelectedText.ToString());
cmd.Parameters.AddWithValue("#Owner", owner.Text);
cmd.Parameters.AddWithValue("#Curncy", curency.Text);
cmd.Parameters.AddWithValue("#Curncytype", curncyval.Text);
cmd.Parameters.AddWithValue("#Depet", Depet.Text);
cmd.Parameters.AddWithValue("#Cridetdevet", textBox5.Text);
cmd.Parameters.AddWithValue("#Date", Date);
cmd.Parameters.AddWithValue("#Note", note.Text);
connection.Open();//Owner
cmd.ExecuteNonQuery();}}
}
catch(Exception ee)
{MessageBox.Show(ee.Message);}
the conforming from the another form
private void button1_Click_1(object sender, EventArgs e)
{
ch.entering(true);
Close();
}
Instead of using the dtab.LoadDataRow, you should be using the dtab.Rows.Add(datarow) method.
An example of how to do this:
public DataTable showout()
{
DataTable dtab = new DataTable();
// More efficient way of adding the columns with types:
dtab.Columns.Add("رقم المتسلسل", typeof(String));
dtab.Columns.Add("رقم الحساب", typeof(String));
dtab.Columns.Add("أسم الحساب", typeof(String));
/*
DataColumn dc1 = new DataColumn("رقم المتسلسل");
DataColumn dc2 = new DataColumn("رقم الحساب");
DataColumn dc3 = new DataColumn("أسم الحساب");
dtab.Columns.Add(dc1);
dtab.Columns.Add(dc2);
dtab.Columns.Add(dc3);
*/
// Create a new row using the .NewRow method
DataRow datRow = dtab.NewRow();
datRow["رقم المتسلسل"] = numb.Text;
datRow["رقم الحساب"] = textBox5.Text;
datRow["أسم الحساب"] = note.Text;
// Add the new row to the DataTable
dtab.Rows.Add(datRow);
return dtab;
}
Reference:
How to: Add Rows to a DataTable
Adding Data to a DataTable
In solve it by the sending the DataTable dt from the first Form cash to the second Form cashagree as a prameter by calling the method that return datagridview
in cash form I wrote this:
cashagree gc2 = cashagree(showout());
in cashagree form I wrote this
DataTable dt = new DstsTsble();
public cashagree(DataTable d2){
dt =d2;
}
and in the load of `cashagree_Load` I asign the datagridview datasoure
private void Cashagree_Load(object sender, EventArgs e)
{
if (dt.Rows[0].IsNull(dt.Columns[0]))
{
MessageBox.Show("There no primary key");
Close();
}
dataGridView1.DataSource = dt;
dataGridView1.Columns[7].Visible = false;// Iwantn't all the datatable so I diapple some Columns
dataGridView1.Columns[5].Visible = false;
dataGridView1.Columns[7].Visible = false;
dataGridView1.Columns[6].Visible = false;
dataGridView1.Columns[4].Visible = false;
}
private void button1_Click(object sender, RoutedEventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("Name");
dt.Rows.Add("1","John");
dataGrid1.ItemsSource = dt.DefaultView;
}
how i can add new row, on click my button? thanks :)
Sample Code :
Dynamically create table, add cloumn, add rows
1- Create a new DataTable
DataTable dt = new DataTable ("Table_AX");
2- Add columns to the DataTable
// Method 1
dt.Columns.Add ("column0", System.Type.GetType ("System.String"));
// Method 2
DataColumn dc = new DataColumn("column1",System.Type.GetType("System.Boolean"));
dt.Columns.Add (dc);
3- To add rows to the DataTable
// Initialize the row
DataRow dr = dt.NewRow ();
dr ["column0"] = "AX";
dr ["column1"] = true;
dt.Rows.Add (dr);
// Doesn't initialize the row
DataRow dr1 = dt.NewRow ();
dt.Rows.Add (dr1);
private void button1_Click(object sender, RoutedEventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("id",System.Type.GetType ("System.String"));
dt.Columns.Add("Name",System.Type.GetType ("System.String"));
DataRow dr=dt.NewROw();
dr[0]="a";
dr[1]="abc";
dt.Rows.Add(dr);
dataGrid1.ItemsSource = dt.DefaultView;
}
Try this code
private void button1_Click(object sender, RoutedEventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("id");
dt.Columns.Add("Name");
DataRow dr = dt.NewRow();
dr["id"]="testid";
dr["Name"] = "testname";
dt.Rows.Add(dr);
dataGrid1.ItemsSource = dt.DefaultView;
}