i m using c# as front end and ms access as back end
I m displaying the datagrid only when the index in the combo box is changed
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
refershGridView(comboBox1.Text);
}
but when I make any updates to the data grid ,the update reflects only after i make a selected index change event
i tried datagidview1.refresh() and also called my refershGridView(comboBox1.Text) functions implicitly
but my grid view refreshes only when i make a selected index change
code for refershGridView(comboBox1.Text)
private void refershGridView(string tableName)
{
saveBttnSwitch = 0;//for save button swicth
//setting back to intial user interface ..
clearVisibilty();
clearall();
button1.Visible = true;
button3.Visible = false;
label11.Visible = false;
try
{
OleDbConnection mycon = new OleDbConnection();
mycon.ConnectionString = ConnString;
//create the database query
string query = null;
if (tableName == "employee")
{
query = "SELECT fname,lname,ssn FROM employee";
dataGridView1.Visible = true;
}
if (tableName == "project")
{
query = "SELECT pname,pnumber FROM project";
dataGridView1.Visible = true;
}
//create an OleDbDataAdapter to execute the query
OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, mycon);
//create a command builder
OleDbCommandBuilder cBuilder = new OleDbCommandBuilder(dAdapter);
//create a DataTable to hold the query results
DataTable dTable = new DataTable();
//fill the DataTable
try
{
dAdapter.Fill(dTable);
}
catch (OleDbException exp)
{
label11.Text = "file couldnt be found...kindly check Db file location ";
label11.Visible = true;
button1.Visible = false;
}
// DataGridView dgView = new DataGridView();
//BindingSource to sync DataTable and DataGridView
BindingSource bSource = new BindingSource();
//set the BindingSource DataSource
bSource.DataSource = dTable;
//set the DataGridView DataSource
dataGridView1.DataSource = bSource;
// dataGridView1.Dock = DockStyle.Fill;
dataGridView1.AutoGenerateColumns = true;
mycon.Close();
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new InvalidOperationException("Data could not be read", ex);
}
this.button2.Visible = false;
}
Does refershGridView(comboBox1.Text); refill the DataGrid?
If so, call it from any other place where you want your data to be refilled. If SelectedIndexChanged even of the combo is the only place you are filling it, it won't refresh unless you change a selection.
And as #Bryan suggests, its better if we see some code.
Try to clear the dTable and dataGridView1.DataSource before you fill the DataTable and sets the DataGridView DataSource
dTable = new DataTable();
dataGridView1.DataSource = nothing;
Related
It works fine when i select all the data from the database and display it. But when i want to specifically display certain data from the database, that error would show up. (System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.' )
private void button1_Click(object sender, EventArgs e)
{
string selectoledb = "Select * from items where Categories=Fitems";
command = new OleDbCommand(selectoledb, connection);
da = new OleDbDataAdapter(command);
DataTable table = new DataTable();
itemstxt.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
itemstxt.RowTemplate.Height = 120;
itemstxt.AllowUserToAddRows = false;
da.Fill(table);
itemstxt.DataSource = table;
DataGridViewImageColumn imageColumn = new DataGridViewImageColumn();
imageColumn = (DataGridViewImageColumn)itemstxt.Columns[3];
imageColumn.ImageLayout = DataGridViewImageCellLayout.Stretch;
DataGridViewButtonColumn button = new DataGridViewButtonColumn();
button.HeaderText = "Buttons";
button.Name = "button";
button.Text = "Add to cart";
button.UseColumnTextForButtonValue = true;
itemstxt.Columns.Add(button);
da.Dispose();
}
you need to add parameter to your select
string selectoledb = "Select * from items where Categories=#Fitems";
command.Parameters.Add("#Fitems", SqlDbType.Varchar).Value = Fitems.Text; //or value you want to filter
So i have a form that looks like this:
Image Link
and I generate the datatable for the dataviewgrid in the load function:
private void loadEmpresas(){
MySqlConnection myConn = new MySqlConnection(gVariables.myConnection);
MySqlCommand command = new MySqlCommand("Select codempresa as 'Codigo', nomempresa as 'Nombre empresa' from contabilidad.empresas", myConn);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = command;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
}
the table in mysql looks like this:
SQL Table Image Link
so when it is running it shows this:
Now the problems that i have are that i have no idea how to modify the width of the columns, id like the entire table to cover that gray space and i want that on click it selects the entire row not just a cell. When it clicks the row i want to pupulate the rest of the textboxes but i have a problem with the click event which for testing purposes is this:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
MessageBox.Show("clicked");
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
MessageBox.Show(row.Cells[0].Value.ToString() + row.Cells[1].Value.ToString());
}
else
{
MessageBox.Show("wat");
}
}
when I click it doesn't even show a messagebox sometimes, I seriously have no idea how to handle the click row event properly :C help please T_T
For updating the column widths try using DataGridViewColumn.width:
DataGridViewColumn column = dataGridView.Columns[0];
column.Width = 60;
DataGridViewColumn.Width property information.
To select the entire row you need to change the SelectionMode of the DataGrid to FullRowSelect:
this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.MultiSelect = false;
SelectionMode information.
I am trying to force DataGrid to refresh its content on a form closing event. I have tried various methods, searched this forum for answers but still I am unable to find a solution.
This is how my DataGridView is being populated :
string strCon = ConfigurationManager.ConnectionStrings["ST"].ConnectionString.ToString();
string strSQL = "SQL QUERY";
SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strCon);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
I have tried the Invalidate method, BindingSource.ResetBindings but still the GridView doesn't refresh. How do I force refresh it?
Data refresh
I think you are talking about data refresh. In this case you can just rebind your DatagridView to the source:
DataGridView dataGridView1 = new DataGridView();
dataGridView1.DataSource = aDataSource;
//Update Data in aDataSource
//...
dataGridView1 = null;
dataGridView1.DataSource = aDataSource;
In your code snapshot aDataSource should actually be bindingSource1. As #GIVE-ME-CHICKEN mentioned, in your case you should enclose the re-binding inside the proper callback to attach it to the right event:
private void Form1_FormClosing(object sender, FormClosingEventArgs e){ ... }
Data refresh
If you don't want to rebind your source you can adopt another solution: binding your dataGridView1 to a Collection Observable. In this case, it will be enough to implement the INotifyCollectionChanged interface to notify the change to its listeners (your DataGridView component)
Graphic refresh
If you are searching only for a graphic refresh, there is a specific method:
dataGridView1.Refresh();
Can you try and change this line:
bindingSource1.DataSource = table;
to
bindingSource1.DataSource = table.DefaultView;
Maybe doing it similar to this way helps?
public DataTable GetData(string SQLQuery)
{
string strCon = ConfigurationManager.ConnectionStrings["ST"].ConnectionString.ToString();
string strSQL = "SQL QUERY";
SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strCon);
SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
//Maybe only one of the clear code works.
dataGridView1.Rows.Clear();
dataGridView1.DataSource = null;
BindingSource bindingSource1 = new BindingSource();
bindingSource1.DataSource = GetData("SQL QUERY");
dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
dataGridView1.ReadOnly = true; //<-----------Try taking this off aswell
dataGridView1.DataSource = bindingSource1;
}
I have a DataGridView made of a DataSet of a table from the DB. When I delete a row, it is updated in the database but it is not removed from the GridView. Only when I restart the application does it get removed from the GridView.
Please help
You need to reset the binding on your bindingsource.
bindingSource.ResetBindings(false);
This is a very simple process.
1.) Create a Binding Source
2.) Set the Datasource for this object to your Dataset Table.
3.) Set The datasource for your DatagridView as the Binding source Object.
Code Example:
Dataset ds = new Dataset();
BindingSource bs = new BindingSource()
bs.Datasource = ds.Table[0];
DatagridView.Datasource = bs;
Now, Any changes you make in the DataTable will ripple through to your GridView automatically.
Hope this helps you?
if you are showing your table in dgv and for deleting something from that table you have a button on your win form. you chose let's say ID and click "delete" button for delting an item from db table. Here is that code:
private void btn_Delete_Click(object sender, EventArgs e)
{
int selectedCellCount = dgv.GetCellCount(DataGridViewElementStates.Selected);
if (selectedCellCount > 0)
{
string selection;
for (int i = 0; i < selectedCellCount; i++)
{
selection = dgv.SelectedCells[i].Value.ToString();
string qs_delete = "DELETE FROM yor_table WHERE id = '" + selection + "';";
try
{
conn = new MySqlConnection(cs);
conn.Open();
cmd = new MySqlCommand();
cmd.Connection = conn;
cmd.CommandText = qs_delete;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (conn != null) conn.Close();
}
}
}
//don't forget to load your table again in dgv
string qs_select = "SELECT * FROM your_table";
System.Data.DataTable dataTable = new System.Data.DataTable();
dataTable.Clear();
dgv.DataSource = dataTable;
try
{
conn = new MySqlConnection(cs);
cmd = new MySqlCommand(qs_select, conn);
conn.Open();
da = new MySqlDataAdapter(cmd);
da.Fill(dataTable);
cb = new MySqlCommandBuilder(da);
dgv.DataSource = dataTable;
dgv.DataMember = dataTable.TableName;
dgv.AutoResizeColumns();
conn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (conn != null) conn.Close();
}
}
You'll notice here that i have MySQL db but don't bother yourself with that.
If database is updated and you want to refresh DataGridView, call this:
this.<table name>TableAdapter.Fill(this.<DB name>DataSet.<table name>);
For example: Where is name of your table (for example Customers) and is name of your database (for example MyDB).
this.CustomersTableAdapter.Fill(this.MyDBDataSet.Customers);
You have to call this function after every deletion(Re-bind Grid).
void BindGrid()
{
YourDataGridView.DataSource = dataset;
YourDataGridView.DataBind();
}
I have a datatable that I am able to populate from my access database without a problem but I want to add a step in it:
private void button_Open_Click(object sender, EventArgs e)
{
var open = new OpenFileDialog
{
InitialDirectory = "c:\\",
Filter = #"Access Files (*.mdb)|*.mdb|All files (*.*)|*.*",
FilterIndex = 0,
RestoreDirectory = true,
Multiselect = false
};
open.ShowDialog();
if (string.IsNullOrEmpty(open.FileName)) return;
try
{
var con = new OleDbConnection();
con.ConnectionString = "Provider= microsoft.jet.oledb.4.0; data source = " + open.FileName;
con.Open();
var dt = new DataTable();
var da = new OleDbDataAdapter("select * from tblCustomerAccount", con);
da.Fill(dt);
dataGridView_AccessDatabase.DataSource = dt.DefaultView;
con.Close();
}
catch (OleDbException ex)
{
//get the error message if connection failed
MessageBox.Show("Error in connection ..." + ex.Message);
}
}
I'd like to add in there a combobox that is populated with the table names then, off the selection of the combobox, the datatable is populated.
How do I populate the combobox with the table names?
Thanks!
//
string[] restrictions = new string[4];
restrictions[3] = "Table";
con.Open();
DataTable tabls=con.GetSchema("Tables",restrictions);
return a datatable that a column of that represent table names
you can bind this datatable to combobox and set datamemebr to TABLE_NAME