No add new row on DataGridView - winforms

Similar to this question DataGridView doesn’t allow user to Delete Row I am using a binding source but I don't visually see the add new line with the * as in the screenshot of the above question. I can select a row and press the delete button and it deletes ok, just cannot add a new row interactively. What I am doing wrong?
NB: My columns are created at design time.
Code to load data is as follows:
Private bindingSource1 As New BindingSource
Private Sub LoadDeploymentNotes(ByVal items As List(Of DeploymentNote))
DataGridView1.AutoGenerateColumns = False
Dim column = CType(DataGridView1.Columns("ColumnChange"), DataGridViewComboBoxColumn)
column.DataSource = [Enum].GetValues(GetType(Change))
bindingSource1.DataSource = items
DataGridView1.DataSource = bindingSource1
DataGridView1.Refresh()
End Sub

Gosh needed a Constructor in my class DeloymentNote that received no arguments.

Related

How can I add a Combobox column to a GridControl?

I have a grid control that loads data from a DataBase in a desktop Windows Forms application. But I also need a new local column with a combobox (with some items) that when I click it it save the information into another table of the database.
This is my code
DataTable dt = new DataTable();
string conStr = #"Data Source =...;Initial Catalog=...; Integrated Security=true;";
SqlConnection con = new SqlConnection(conStr);
SqlCommand com = new SqlCommand("SPS_PronosticoStock2", con);
com.Parameters.AddWithValue("#IdProducto", Convert.ToInt32(textBox3.Text));
com.Parameters.AddWithValue("#IdBodega", Convert.ToInt32(textBox4.Text));
com.Parameters.AddWithValue("#FechaInicio", dateTimePicker1.Value);
com.Parameters.AddWithValue("#FechaFin", dateTimePicker2.Value);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
try
{
con.Open();
da.Fill(dt);
}
catch (Exception)
{
throw;
}
finally
{
if (con.State == ConnectionState.Open)
con.Close();
}
gridControl1.DataSource = dt;
I tried a combobox edit but when i click the items they disappear and nothing is edited, please someone help me with this.
Refer these:
Unbound Column Combo Box Persistent Value
Use Unbound Columns. Please review the Unbound Columns article for more information in this regard.
The best way to get it done is to use RepositoryItemLookUpEdit instead. Just set theRepositoryItemLookUpEdit.DataSource property to an appropriate datasource, the RepositoryItemLookUpEdit.DisplayMember property - to a column name that should match a display text and the RepositoryItemLookUpEdit.ValueMember property - to a column name that should be associated with an edit value.
References:
Combobox within Xtragrid bound to column value
XtraGrid with comboBox column doesn't save value in grid
https://www.youtube.com/watch?v=bbNhg1Xn9O4
Your values are not being saved, because your column is not bound to a data field. Create an Unbound Column and save your values in the CustomUnboundColumnData event handler.

Populate a combobox with in vb.net based on a selection of another combo box from databse

I have 2 combo boxes and a couple of labels, the thing is I want to pull up data from one of my database columns which is the drug_group and after that I want whenever I select a drug group from the first combo box the corresponding drug name from the database should be populated on the second combobox. And after that the labels should pull the drugs information. My issue here is that the first combobox does get populated but it kinda repeats some of the data. and then when I select any of the item from the first combo box thesame items get displayed. Below is my code and screenshot is attached of my progress so far. I just want to know how to go about it thanks.
Private Sub storeform_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
'TODO: This line of code loads data into the 'PhermacyDataSet.tblsolddrugs' table. You can move, or remove it, as needed.
Me.TblsolddrugsTableAdapter.Fill(Me.PhermacyDataSet.tblsolddrugs)
'TODO: This line of code loads data into the 'PhermacyDataSet1.tbldrug' table. You can move, or remove it, as needed.
'Drug Group Combo box
Dim connString As String = "Data Source=.\SQLEXPRESS;Database=phermacy; Integrated Security = true"
Dim conn As New SqlConnection(connString)
Dim strSQL As String = "SELECT * FROM tbldrug"
Dim da As New SqlDataAdapter(strSQL, conn)
Dim ds As New DataSet
da.Fill(ds, "tbldrug")
With cmbdruggp
.DataSource = ds.Tables("tbldrug")
.DisplayMember = "Drug_group"
.ValueMember = "Drug_ID"
.SelectedIndex = 0
End With
'Drug Name combo
Dim strSQL1 As String = "SELECT Drug_Name FROM tbldrug WHERE Drug_group =" & Me.cmbdruggp.SelectedValue
Dim da1 As New SqlDataAdapter(strSQL1, conn)
Dim ds1 As New DataSet
da.Fill(ds1, "tbldrug")
With cmbdrugname
.DataSource = ds1.Tables("tbldrug")
.DisplayMember = "Drug_Name"
.ValueMember = "Drug_group"
.SelectedIndex = 0
End With
End Sub
My form layout
You need to implement an event handler for the SelectedIndexChanged event of your first combobox, and put the code that finds the contents of the second combo box there. You can create the event handler easily by double clicking the drug group combo box in the designer.
before every new load of items use the method cmbdrugname.Items.Clear() and than you would not have multiple identical items.
try to create a selectedindexchange (by double clicking on combobox) the type code like:
if cboName.text = "value" then
cboName.add.item(value)
end if

Manually adding a new row to DataGridView does not immediately update the bound DataTable

I have a c# windows form app written in .net-4.0
I have a datagridview (dgvItems) which I programmatically bind to a dataset and datatable at the end of an import function.
I have an import button that imports data from a selected excel file into a table called _dtItemAdjustList, once the data has been imported I bind that table to my grid. The code I use to bind the grid is:
dgvItems.DataSource = _dsQtyAdjust;
dgvItems.DataMember = "Item Adjust List";
dgvItems.Refresh();
Everything works fine so far, if I edit the imported data in the datagridview, it updates the bound table _dtItemAdjustList after each cell is edited.
My issue comes in when I try to manually add a row to my datagridview, it doesn't immediately add that new row to the bound datatable.
Example: I put a break point at the end of my dgvItems_CellValueChanged event and added a _dtItemAdjustList.Rows.Count watch and here is what happens.
After the data is imported and I edit one of the existing imported lines the watch shows the correct row count, lets say 5.
Now I click the last * row, and type something into my item# column and hit tab, the break point fires but my row count still only shows 5, I fill out a few more cells in the new row but each time I leave a cell and my CellValueChanged event fires and the row count remains at 5.
Next I add a second manual row, now immediately after I tab out of the first cell I filled out for this second new row, my row counter goes to 6, but technically at this point I've added 2 manual rows to my imported 5, so the counter should read 7
This repeats, basically each new manually added row to the datagridview isn't added to the bound datatable until either a) another row is added or b) I go back and re-edit a cell on an existing row.
Edit
Forgot to mention I tried binding my DataGridView two ways:
DataSource = _dsQtyAdjust //dataset Name
DataMember = "Item Adjust List" // Table Name in the dataset
DataSource = _dtItemAdjustList
It made no difference as far as my new row behaviour goes.
Ok after a lot of trial and error and online searching I found a solution that seems to work.
Instead of binding my DataGridView directly to my DataTable, I created a BindingSource, bound the BindingSource to my DataTable, then bound my DataGridView to the BindingSource and finally in my dgvItems_CellValueChanged event I used a combination of EndEdit() and NotifyCurrentCellDirty(true/false) to make it work.
Code sample:
public partial class frmQuantityAdjustment : Form
{
// In my forms partial class I created a new public BindingSource
public BindingSource bsItemAdjust = new BindingSource();
}
private void frmQuantityAdjustment_Load(object sender, EventArgs e)
{
// In my form_Load event I bound the BindingSource to my DataTable
// and then the DataGridView to the BindingSource
bsItemAdjust.DataSource = _dtItemAdjustList;
dgvItems.DataSource = bsItemAdjust;
dgvItems.Refresh();
}
private void dgvItems_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
// Finally at the end of my CellValueChanged event I added the
// following code
bsItemAdjust.EndEdit();
dgvItems.NotifyCurrentCellDirty(true);
dgvItems.EndEdit();
dgvItems.NotifyCurrentCellDirty(false);
}
I came across this solution on this thread and after some testing it seems to work perfectly.
Now the new row in my DataGridView is added to the bound DataTable at the end of the CellValueChanged event.

Why will my Datagridview not display information from the DataTable to which I bound it?

I have created a form with a datagridview on it. I bound that DGV to a datatable which is constructed from a table in a SqlServer CE database. I was able to add, edit and delete records and save changes to the database.
Then, I set AutoGenerateColumns to False so I could set up the DGV with nice formatting. To begin, I added only one column:
'/// Set Up DataGridView
With dgvMaterials
.AutoGenerateColumns = False
'.Columns.Add("MaterialName", "Material")
End With
Dim col As DataGridViewColumn
'
col = New DataGridViewColumn
With col
.Name = "Material"
.DataPropertyName = "MaterialName"
.Width = 200
'.HeaderText = "Material"
End With
dgvMaterials.Columns.Add(col)
dgvMaterials.DataSource = stuff.Materials
(Stuff is an instance of a class where I do my SQL stuff, Materials is the name of the DataTable)
Now I must have checked DataPropertyName a hundred times and I verified that there are records in the DataTable, but they will not show in the DGV. Why?
As always thanks in advance for any help offered.
Folks, the answer is simple: I put my column in as type DataGridViewColumn and for whatever reason it had to be DataGridViewTextBoxColumn to work. I switched it out, now the datagridview works like a champ.

Reload the DataGridView when changes occur to its dataset vb.net

I have a DataGridView control in my windows form application. What i want to do is this:
I want to reload the view so that it shows the correct data when a change occur to the database table that it is bound.
In other words, when i delete a record, using an sql query not the DataGridView1.Rows.Remove(DataGridView1.CurrentRow) property, i want the changes to occur to the datagridview also.
For example: I have a customers table that is bound to the datagridview. When i delete a record, lets say the one with ID=5, i want the row to be removed from the gridview in run-time. Is this possible?
EDIT:
I am calling this procedure every time i delete a customer in order to re-bind the datasource
Private Sub reloadDataset()
DataGridView1.DataSource = ""
DataGridView1.DataSource = CustomerBindingSource
End Sub
It does not work though....What am i doing wrong?
Thanks for your effort..
EDIT 2
Just to clarify: CustomerBindingSource has DataSource(myDatasource) and datamember the table customers
I can't tell from the limited code you have posted, but if you are using a BindingSource you need to make sure you are reloading it's DataSource, not the DataGridView DataSource. The DataGridView can stay bound to the same BindingSource:
Private Sub Load()
'Tell DataGridView to use BindingSource.
DataGridView1.DataSource = CustomerBindingSource
'Fetch the table.
'Tell the BindingSource what you want it to wrap/use as it's DataSource.
CustomerBindingSource.DataSource = FetchData()
End Sub
Private Sub Reload()
'We have made some changes and need to refresh/reload.
'We need to re-fetch the table and re-bind it to BindingSource's DataSource.
CustomerBindingSource.DataSource = FetchData()
End Sub
Private Function FetchData() as DataTable
Using Conn As New Data.SqlClient.SqlConnection("connectionString"),
Command As New Data.SqlClient.SqlCommand("SQLQuery", Conn),
Adapter As New Data.SqlClient.SqlDataAdapter(Command)
Dim Table As New DataTable
Adapter.Fill(Table)
Return Table
End Using
End Function
FetchData returns a datatable that the BindingSource can bind to, but you could return any object that can be bound. Note that this implementation of FetchData is specific to SQL Server.

Resources