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;
}
Related
I am trying to display my mysql database table on a DataGridView using c# . but nothings happening . please tell me where i've gone wrong in my code
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection conn = new MySqlConnection("Server = localhost; Database=project; user=root;password=''");
conn.Open();
string query = "SELECT * FROM billing";
MySqlDataAdapter bills = new MySqlDataAdapter(query, conn);
MySqlCommandBuilder cbuilder = new MySqlCommandBuilder(bills);
DataTable dtable = new DataTable();
bills.Fill(dtable);
//the DataGridView
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
dgView.DataSource = bSource;
bills.Update(dtable);
}
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 have a Database with 2 Tables. Now i want to search for Values in my Databases.
I use this GUI so the "User" can give Information to the Textbox and the searched Values should shown in my Datagridview
I use this Code:
private void TB_MSGHeadline_TextChanged(object sender, EventArgs e)
{
try
{
if (TB_MSGHeadline.Text.Equals(""))
{
}
else
{
DataView dv = new DataView(table);
dv.RowFilter = string.Format("MessageHeadline LIKE '%{0}%'", TB_MSGHeadline.Text);
dataGridView1.DataSource = dv;
}
}
catch (Exception i)
{
MessageBox.Show("" + i);
}
}
Fill the DataGridview
private void GetData(string selectCommand)
{
//Creating a new data adapter based on the specified query.
dataAdapter = new SqlDataAdapter(selectCommand, ConnectionString);
//Create a command builder to generate SQL update, insert, and
//delete commands based on selectCommand. These are used to
//update the Database.
SqlCommandBuilder CommandBuilder = new SqlCommandBuilder();
//Populate a new data table and bind it to the BindingSource
DataTable table = new DataTable();
table.Locale = System.Globalization.CultureInfo.InvariantCulture;
dataAdapter.Fill(table);
BindingSource1.DataSource = table;
}
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = BindingSource1;
GetData("SELECT * FROM Tabelle1");
}
(Found it in a video but dont work for my problem)
But i get the Error, that the row "MessageHeadline" wasnt found
So i want to know, how can i make a LIKE search for my SQL Database?
So i have a website hosted on blacknight.com. Im coding with cSharp and asp.net I have mySQL database stored within blacknight also.
However I want to add an admin section to my site where a user could log in and press a "load data" button and the registration table values from blacknight database would appear in a grid view.
However its just not working. Im wondering do I have to physically connect my gridview to my database? Because I have tried to connect to my hosted database with my gridview and it keeps saying it cant connect.
Below is the code behind my load data button. As as it stands when I upload my adminpages to blacknight and run, the gridview is not even appearing. This is my Fourth year project for college and I really need to get it working. Any help would be much appreciative.
protected void Button1_Click(object sender, EventArgs e)
{
string constring ="Server=xxxx; Database=xxxx; Uid=xxx; Pwd=xxx";
MySqlConnection conDb1317466_bk = new MySqlConnection(constring);
DataSet dbdataset = new DataSet();
//binding.DataSource = this.bindingSource.DataSource;
MySqlCommand cmdDb1317466_bk = new MySqlCommand("Select * from db1317466_bk.registration;", conDb1317466_bk);
try
{
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = cmdDb1317466_bk;
DataTable dbdataset1 = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
//DataGridView1.DataSource = bSource;
DataGridView1.DataBind();
sda.Update(dbdataset);
}
catch (Exception)
{
Page.ClientScript.RegisterStartupScript(this.GetType(), "scriptkey", "<script>alert('Can Load data');</script>");
}
}
}
Try this one
GridView1.DataSource=dbdataset;
GridView1.DataBind();
Instead of using
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
DataGridView1.DataBind();
Also, I don't think that you should use:
sda.Update(dbdataset);
Try this
try
{
MySqlDataAdapter da = new MySqlDataAdapter();
da.SelectCommand = cmdDb1317466_bk;
DataTable dt= new DataTable();
da.Fill(dt);
DataGridView1.DataSource = dt;
DataGridView1.DataBind();
}
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;