How to bind DataRow from DataSet? - c#

I have a DataSet that contains values returned by my WCF function, as below:
DataSet ds = IserviceClient.FunctionMe(dcClient, dcBook);
#region show to dgv_item
DataTable dt1 = ds.Tables[0];
DataRow dr1;
int rc = dt1.Rows.Count;
clsMessageBoxes.ShowInfo(rc.ToString()); // Here show the number of row, so far the row is show the right value
//from here how to pass the row in that datatable to my datagridview? i
for (int i = 0; i < rc; i++)
{
dr1 = dt1.Rows[i];
dgv_item.Rows.Add();
dgv_item.Rows[i].Cells["dgvc_no"].Value = dr1["cnNo"].ToString();
dgv_item.Rows[i].Cells["dgvc_ID"].Value = dr1["cnID"].ToString();
dgv_item.Rows[i].Cells["dgvc_Name"].Value = dr1["cnName"].ToString();
}
Using this, I get the error
Rows cannot be programmatically added to datagridview's rows collection when the control is data-bound
Why do I get this, and how can I resolve it?

Related

how add new data to data grid view without delete data C#?

hello guys need to put data on data grid view without delete this my code but this code give me only last item in list box
for (int i = 0; i < listBox1.Items.Count; i++)
{
textBox1.Text = listBox1.Items[i].ToString();
dataGridView1.DataSource = cls_all.Get_Test3(Convert.ToSingle(textBox1.Text));
}
tried this code
dataGridView1.Rows.Add(cls_all.Get_Test3(Convert.ToSingle(textBox1.Text)));
and get this msg System.InvalidOperationException: 'Rows cannot be programmatically added to the DataGridView's rows collection when the control is data-bound.'
need way to put data without delete data grid view any help with it
Use a DataTable instead of directly trying to add rows to a grid.
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("MyColumn", typeof(String));
dt.Columns.Add(dc);
for (int i = 0; i < listBox1.Items.Count; i++)
{
textBox1.Text = listBox1.Items[i].ToString(); // I do not know why you need this
dt.Rows.Add(new Object[] { listBox1.Items[i].ToString()});
}
dataGridView1.ItemsSource = dt.DefaultView;

How to rows dynamically in datagrid C# wpf?

I want to set number of rows of datagrid equal to a number given by user in a textbox.
means if i enter 6 in the textbox, it should add 6 rows in the datagrid.
thats what i want. I may be wrong.
But Null exception is being thrown.
How to fix my issue?
Here is the code:
DataTable dt;
DataRow dr;
int rownumber=0;
dt = new DataTable("emp2");
DataColumn dc3 = new DataColumn("Wi", typeof(double));
DataColumn dc4 = new DataColumn("Hi", typeof(double));
rownumber = Int32.Parse(txtBexNumber.Text);
dr[rownumber] = dt.NewRow();
dt.Rows.Add(dr);
dt.Columns.Add(dc3);
dt.Columns.Add(dc4);
datagrid1.ItemsSource = dt.DefaultView;
You're creating a DataTable, then trying to immediately access a user-specified row in the table even though no rows have been added yet.
Use a loop to add rows first
for(int i = 0; i < rowNumber; i++)
{
dr = dt.NewRow();
dt.Rows.Add(dr);
}
As a side note, when working with WPF its easier to work with an ObservableCollection of objects instead of DataTables and DataRows. The data is much easier to understand and work with instead of trying to use DataRows and DataColumns.
var data = new ObservableCollection<MyObject>();
for (int i = 0; i < rowNumber; i++)
data.Add(new MyObject() { Wi = 0, Hi = 0 });
dataGrid1.ItemsSource = data;
I guess it´s better to use
Int32.TryParse(txtBexNumber.Text, out rownumber);
(maybe you get the error for parsing an empty string? If possible try to debug where exactly the null pointer exception accurs)
Also validate if
dr[rownumber] = dt.NewRow();
works as expected. If e.g. dr[10] doesn´t exist, you get an exception.

How to programmatically add rows to DataGrid in C#?

So as the title states, I'm trying to add rows to a DataGrid programmatically using C# but I can't seem to make it work. This is what I have so far.
// I have a DataGrid declared as dg in the XAML
foreach (string s in array) {
int index = 0;
DataGridRow dgRow = new DataGridRow();
foreach (DataGridColumn dgColumn in columns)
{
// Trying to add Text to dgRow here but IDK how
index++;
}
}
I've been googling around and the closest I got to adding anything was to use {column = value} but it just throws me an error. Really out of ideas now though :\
Here's you can do it better way by binding a source to datagridview
// Creating DataSource here as datatable having two columns
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Name");
// Adding the rows in datatable
for (int iCount = 1; iCount < 6; iCount++)
{
var row = dt.NewRow();
row["ID"] = iCount;
row["Name"] = "Name " + iCount;
dt.Rows.AddRow(row);
}
DataGridView dgv = new DataGridView();
// Set AutoGenerateColumns true to generate columns as per datasource.
dgv.AutoGenerateColumns = true;
// Finally bind the datasource to datagridview.
dgv.DataSource = dt;
In Case you are using WPF DataGrid
you can bind it like this way-
dgv.DataContext = employeeData.DefaultView;
and in
XAML
<DataGrid Name="dgv" ItemsSource="{Binding}">
//create datatable and columns,
DataTable dtable = new DataTable();
dtable.Columns.Add(new DataColumn("Column 1"));
dtable.Columns.Add(new DataColumn("Column 2"));
//simple way create object for rowvalues here i have given only 2 add as per your requirement
object[] RowValues = { "", "" };
//assign values into row object
RowValues[0] = "your value 1";
RowValues[1] = "your value 2";
//create new data row
DataRow dRow;
dRow = dtable.Rows.Add(RowValues);
dtable.AcceptChanges();
//now bind datatable to gridview...
gridview.datasource=dbtable;
gridview.databind();
Regards
did you try?:
int n=5; // number of rows you want to add
dataGridView1.Rows.Add(n);
// you can add (names of the rows) if you have them in your array
//for(int i=0; i<n; i++)
//dataGridView1[0, i].Value = array[i];

datarow filter value to datatable

I want to insert data row filter value to datatable but it returns the following error "This row already belongs to another table." Please help me to fix this error..
This is my partial code :
for (int j = 0; j < ListBox1.Items.Count; j++)
{
DataView DV = new DataView();
DV = DS1.DefaultView;
DV.RowFilter = "fldemployee='" + ListBox1.Items[j].Text + "' and fldassigndate = '04-07-2012'";
if (DV.Count > 0)
{
DataTable table = DV.ToTable("sp_getallattendancesetup");
DataRow row = table.Rows[0];
DT.Rows.Add(row);
}
}
GridView1.DataSource = DT;
GridView1.DataBind();
You can use ImportRow
DT.Rows.ImportRow(row);
Information from msdn: Calling NewRow adds a row to the table using
the existing table schema, but with default values for the row, and
sets the DataRowState to Added. Calling ImportRow preserves the
existing DataRowState along with other values in the row. If the
DataRow that is passed as a parameter is in a detached state, it is
ignored, and no exception is thrown.
The new row will be added to the end of the data table.
If the new row violates a Constraint it won’t be added to the data
table.
You can get the index of the new row with as DataTable.Rows.Find and
DataTable.Rows.IndexOf. See DataRowCollection and Rows for more
information.
Reference here

Getting a dataset from an unbound datagridview

I have a datagridview that is not bound directly do a datasource. Instead, I add the data from various methods during runtime. I created a method that accepts a dataSet and outputs it into Excel, but I can't find if there is an in-built way to geta dataSet from a dataGridView.
Thanks.
I updated the code to work. There was a few typos in the previous answer.
DataTable dt = new DataTable();
for (int i = 0; i < dgvPaperAndPlastic.Columns.Count; i++)
{
DataColumn column = new DataColumn(dgvPaperAndPlastic.Columns[i].HeaderText);
dt.Columns.Add(column);
}
int noOfColumns = dgvPaperAndPlastic.Columns.Count;
foreach (DataGridViewRow dr in dgvPaperAndPlastic.Rows)
{
//Create table and insert into cell value.
DataRow dataRow = dt.NewRow();
for (int i = 0; i < noOfColumns; i++)
{
dataRow[i] = dr.Cells[i].Value.ToString();
}
}

Categories

Resources