Updating DataGridViews source programmatically? - c#

After I change the DataGridView cell's value programmatically, the source cannot be updated. What can I do?
datagridview1.DataSource = bindingsource1;
datagridview1.Rows[0].Cells[0].Value = "1";

You need to call refresh on datagridview
datagridview1.Refresh();
If you are in edit mode then you should use EndEdit
datagridview1.EndEdit();
datagridview1.Refresh();

I think you need to do this manually. Bind the data to the gridview. Update the gridview. Select the cell that was updated, save the data back to the data and pull the data from the datasource and refresh the gridview.

You need write back the DataSet, here below my codes
private void button2_Click(object sender, EventArgs e)
{
this.Validate();
try
{
dgvArticles.CurrentRow.Cells[1].Value = txtSubject.Text;
dgvArticles.CurrentRow.Cells[2].Value = rtbBodyContent.Text;
dgvArticles.CurrentRow.Cells[3].Value = pbPrimaryPicture.Image;
dgvArticles.CurrentRow.Cells[4].Value = pbSecondaryPicture.Image;
dgvArticles.CurrentRow.Cells[5].Value = pbThirdPicture.Image;
}
catch
{
MessageBox.Show(e.ToString());
}
AccessingNetFamerDatabase anfdArticles = new AccessingNetFamerDatabase();
if (_dsArticles!= null)
{
SqlCommandBuilder _sqlCBArticles = new SqlCommandBuilder(AccessingNetFamerDatabase._sqlDataAdapter);
AccessingNetFamerDatabase._sqlDataAdapter.Update(_dsArticles.Tables[0]);
}
}

I has the same issue, was able to solve it by calling EndEdit() on the binding source.
eg
bs.EndEdit();
int x1 = data.Update(dt);
Update then returned the number of rows updated. Before the EndEdit was added it was constantly zero

Related

C# My BindingSource filter won't seems to update dataGrid

I've tried updating dynamically my datasource on my datagrid, but it keeps returning no value... Note : i've already closed my connection to my SQL database and am tried to filter it through a textbox textchanged method (at each change, it would dynamically filter the Binding).
It seems my textbox and everything is populated at each step i've checked each propert, and yes, my column to be filtered is verb
void txtChanged(object sender, EventArgs e)
{
TextBox tbTemp = (TextBox)sender;
DataTable dt = new DataTable();
dataSet.dataAdapter.Fill(dt);
BindingSource bs = new BindingSource();
bs.DataSource = dt;
bs.Filter = string.Format("[{0}] LIKE '%{1}%'", "Verb", tbTemp.Text);
dataGrid.DataSource = bs;
}
}
Thanks in advance for the help!
Oh my god, guys. it works like a charm now! Thanks for the help, i would like to help any other people with this issue. It was sooooo complex... Your solution guided me towards the truth :
BindingSource datamember property needs to be set to table. Here is my correct code :
void txtChanged(object sender, EventArgs e)
{
TextBox tbTemp = (TextBox)sender;
dataSet.bdSource.Filter = string.Format("[{0}] LIKE '%{1}%'",
strTemp[Int16.Parse(tb.Name)], tbTemp.Text);
//Use table name instead of verb
dataSet.bdSource.DataMember = "Verbe";
dataGrid.DataSource = null;
dataGrid.DataSource = dataSet.bdSource;
dataGrid.Refresh();
}

Adding a row to datagridview with information

I have datagridview that contains information from my database. But I need to add new rows with a button.
This error message appears:
Rows cannot be programmatically added to the datagridview's row collection when the control is data-bound
private void pictureBox1_Click(object sender, EventArgs e)
{
int rowId = dgvArticulos.Rows.Add(new DataGridViewRow());
}
I read many posts but they're using DataTable and it doesnt work for my case. Does anybody knows how to solve this issue?
Thanks in advance
I solve my problem. I created a new List and set the value of my DataSource. After that, I was able to add a row to the new list. It works perfect
List<Documento_Articulo> listaDA = lista;
listaDA.Add(new Documento_Articulo());
dgvArticulos.DataSource = null;
dgvArticulos.DataSource = listaDA;

add the new row client has entered to data source on radgirdview

I am new to using the telerik tools for winforms and I was wondering if anyone could help me to find the best way so that the client can add a new row on the radgrid and for it to show this change on the data source.
so far I have the radgrid set up so that the client can add a new row. I just need to bind it to the data source.
private void radGridView1_Click(object sender, EventArgs e)
{
this.radGridView1.AllowEditRow = false;
this.radGridView1.AllowAddNewRow = true;
this.radGridView1.AllowDeleteRow = false;
this.radGridView1.AddNewRowPosition = Telerik.WinControls.UI.SystemRowPosition.Top;
this.radGridView1.MasterTemplate.AddNewBoundRowBeforeEdit = true;
radGridView1.EnableAlternatingRowColor = true;
}
Have a look at the UserAddedRow event for RadGridView. This is fired after the user added a new row to the grid. You could then add the new entries to a source list or data table.
List<Foo> _lSource = new List<Foo>();
DataTable _tSource = new DataTable();
private void radGridView1_UserAddedRow(object sender, GridViewRowEventArgs e)
{
Foo foo = new Foo();
foo.Col1 = e.Row.Cells["col1"].Value.ToString();
foo.Col2 = e.Row.Cells["col2"].Value.ToString();
_lSource.Add(foo);
_tSource.Rows.Add(e.Row.Cells["col1"].Value.ToString(), e.Row.Cells["col2"].Value.ToString());
}
I added both possibilities in the same code snippet. Just choose one (list or table). I just created a random class to show you an example. You can create your own classes and name the properties as you want. Just note that the column (col1 and col2 in my example) must exist, otherwise you'll get a NullReferenceException. If you're using DataTable you have to add the columns once before adding rows.
_tSource.Columns.Add("col1");
_tSource.Columns.Add("col2");
I also recommend not to update the RadGridView properties on a click event of RadGridView. Because it is enough to set those properties once. Now you set them every time you click in your grid view. Either move them to the Load event of your form or set it directly in designer properties.
private void Form_Load(object sender, EventArgs e)
{
radGridView1.AllowEditRow = false;
radGridView1.AllowAddNewRow = true;
radGridView1.AllowDeleteRow = false;
radGridView1.AddNewRowPosition = Telerik.WinControls.UI.SystemRowPosition.Top;
radGridView1.MasterTemplate.AddNewBoundRowBeforeEdit = true;
radGridView1.EnableAlternatingRowColor = true;
}
RadGridView supports data binding to variety of data sources and CRUD operation will be handled for you automatically. Here you can find information on the supported data sources: Telerik UI for WinForms Documentation
And here is how to bind to a DataTable, where all CRUD operations work out of the box
RadGridView radGridView1 = new RadGridView();
this.Controls.Add(radGridView1);
radGridView1.Dock = DockStyle.Fill;
DataTable table = new DataTable();
table.Columns.Add("col1");
table.Columns.Add("col2");
table.Rows.Add("value1", "value1");
table.Rows.Add("value2", "value2");
radGridView1.DataSource = table;
Here is also a design time tutorial.

How to select full DataGridView and update it?

Here in Form1(), I am getting all data from db1. In btnGetDb1_Click() is the code to update db2 database. This is successful on selecting specific row from dataGridView1. How to implement this without selecting any row from dataGridView1 and updating all the rows together?
public Form1()
{
InitializeComponent();
DataSet dsForDb1 = new DataSet();
dsForDb1 = client.GetAllFromDb1(); // Got All The Data From db1
dataGridView1.DataSource = dsForDb1.Tables[0];
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells);
}
private void btnGetDb1_Click(object sender, EventArgs e)
{
// Start Updating from db1
ServiceReference1.UserDetails objuserdetail =
new ServiceReference1.UserDetails();
objuserdetail.ID = (int)dataGridView1.CurrentRow.Cells[0].Value;
objuserdetail.Name = (string)dataGridView1.CurrentRow.Cells[1].Value;
objuserdetail.Age = (string)dataGridView1.CurrentRow.Cells[2].Value;
client.UpdateDb2(objuserdetail); // To Update the Data
MessageBox.Show("Data Updated Successfully");
client.Close();
}
The DataBound event on dataGridView1 will fire when the data bind is complete. At this point, you can iterate over the GridView.Rows collection to get the data you need for the update of the second database.
How that is done is dependent really on the database you are using and the number of rows you're likely to have in dataGridView1 - ideally, you don't want to be firing a separate query for every row if there are going to be hundreds of them, so look at using a table valued parameter or equivalent if your DBMS permits.
private void dataGridView1_DataBound(object sender, EventArgs e)
{
foreach (GridViewRow row in dataGridView1.Rows)
{
......
}
}

Checkbox in datagrid view doesn't update my bindingList

I have a datagrid with 2 columns. One is a checkbox and one is a normal textbox cell. All is bound to one BindingList which is an entity.
If I check one checkbox and then loop to get the checked entities from the BindingList, it returns nothing. But if I check then edit the textbox column, it works just fine and return one result.
I tried to refresh or to check then click somewhere else. It doesn't work.
How do you manage to get your bindingList updated when you check a column?
Thank you!
What data type is the column in the data source (dataTable)? Is it boolean type?
But this doesnt matter so much, what matters is that you use the correct event of the dgv.
Use:
1. CurrentCellDirtyStateChanged and
2. CellValueChanged
This is the code you have to use:
private void CreateAndBind()
{
DataTable table = GetDataToDataTable();
//then bind it to dgv:
dgv.DataSource = new BindingSource(table, null);
//create events for dgv:
dgv.CurrentCellDirtyStateChanged += new EventHandler(dgv_CurrentCellDirtyStateChanged);
dgv.CellValueChanged += new EventHandler(dgv_CellValueChanged);
}
private DataTable GetDataToDataTable()
{
//get data from dataBase, or what ever...
table.Columns.Add("column1", typeof(stirng));
table.Columns.Add("column2", typeof(bool));
//adding some exmaple rows:
table.Rows.Add("item 1", true);
table.Rows.Add("item 2", false);
return table;
}
void dgv_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
if (dataGridView1.IsCurrentCellDirty)
dataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit);
}
private void dgv_CellValueChanged(object obj, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0) //compare to checkBox column index
{
DataGridViewCheckBoxCell check = dataGridView1[0, e.RowIndex] as DataGridViewCheckBoxCell;
if (Convert.ToBoolean(check.Value) == true)
{
//If tick is added!
//
}
}
}
Hope it helps.

Categories