How to save GridView to DataBase in WPF? - wpf

in C# I often do it this way:
Load Table from DataBase to GridView
SqlCeDataAdapter dataAdapter;
try
{
String connectionString = connStr;
String selectCommand = "select * from Table_Name";
dataAdapter = new SqlCeDataAdapter(selectCommand, connectionString);
commandBuilder = new SqlCeCommandBuilder(dataAdapter);
DataTable table = new DataTable();
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
DataGridView1.DataSource = bindingSource1;
}
catch (SqlCeException ex)
{
MessageBox.Show(ex.Message);
}
After do same(much) changes on GridView Cell, I save it to Database this way:
dataAdapter.Update((DataTable)bindingSource1.DataSource);
Assume I load the table to GridView the same way in WPF. How to save all GridView value to database? (in WPF way :P)
NB: I'm using SQL Server CE for database.

Date table is a valid data source in wpf, you can do the binding with it(with ItemsSource property), and the saving procedure is not really related to the data grid.
just hold a reference to your table.

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.

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.

How to bind DataGridView from Database after selecting value from combox

I am making a Windows Form in C#.I have a DataGridView, all I need to bind this grid view to database with a where clause and whose value will be equal to combobox selected item.
I have done something like this:
private void combsalesid_SelectedIndexChanged(object sender, EventArgs e)
{
SqlCommand cmr = DataConnection.GetConnection().CreateCommand();
cmr.CommandText = "select * from SalesOrder where SalesId = #salesis";
cmr.Parameters.Add(new SqlParameter("#salesis", combsalesid.SelectedItem.ToString()));
SqlDataAdapter da = new SqlDataAdapter(cmr);
DataSet ds = new DataSet();
da.Fill(ds);
grdsalesorder.DataSource = ds;
cmr.Dispose();
DataConnection.CloseConnection();
}
But it's not working.
What is the value of combsalesid.SelectedItem.ToString()?
I guess combsalesid is bound to a Datatable, so
Selecteditem.ToString() returns the container object (a
System.Data.DataRowView).
If yes, you just need to cast the SelectedItem into DataRowView in
order to get a value from this DataRowView.
Take a look at this post,
listbox selected item give me " System.Data.DataRowView" , C# winforms.
It refers to ListBox but it is the same issue.
Then when you assign a Dataset as DataSource for your DataGridvView, you need also to set the DataMember property which would be the name of the DataTable. Another way is to pass the DataTable as datasource.
grdsalesorder.DataSource = ds.Tables(0);

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.

Datagrid bind in wpf with one static column and rest dynamic

I am working on WPF where i have to bind datagrid.I try my best to explain my problem if any doubt then please ask.
I am able to bind datagrid by using following code :
XAML view :
<DataGrid Height="257" HorizontalAlignment="Left" Margin="20,12,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="Auto"></DataGrid>
CS view :
SqlDataAdapter da = new SqlDataAdapter("select staticcolumn,column1,column2,column3,column4 from TBL_SENSORS", connection);
DataSet ds = new DataSet();
da.Fill(ds, "SensorZones");
dataGrid1.ItemsSource = dataset.Tables[0].DefaultView;
ataGrid1.DataContext = dataset.Tables[0];
this code give me a grid with default column names passed from database.
But problem is that in my application i have one combobox from where i have to select column names like column1,column2.On the bases of this selection i have to bind datagrid with these columns only but in all cases i want my staticcolumn is present with modified name Date Recorded and rest selected column with default name.
Thanks
Personally I would much rather use linq
However, what you need to do is have a seperate query based off of each item in the combobox.
Something like :
public string SelectedComboboxItem
{
get
{
return _selectedComboboxItem;
}
set
{
_selectedComboboxItem = value;
OnPropertyChanged(SelectedComboboxItem);
SqlDataAdapter da;
select (_selectedComboboxItem)
{
case "Column 1":
da = new SqlDataAdapter("select staticcolumn,column from TBL_SENSORS", connection);
case "Column 2":
da = new SqlDataAdapter("select staticcolumn,column2 from TBL_SENSORS", connection);
//All the other queries go here
}
DataSet ds = new DataSet();
da.Fill(ds, "SensorZones");
dataGrid1.ItemsSource = dataset.Tables[0].DefaultView;
dataGrid1.DataContext = dataset.Tables[0];
}
}
So you bind your combobox's selected item to this property (you need to implement INotifyPropertyChanged) and then you should have a different datasource for each selection. Unfortunately this should reset the datagrid, so I'm not sure if this is what you are looking for.
Alternatively you could just create a converter and bind the Combobox's selecteditem to the columns' visibility property if you just want to make the columns invisible.

Resources