Reputation: 163
Hi everyone I have a DataGridView, inside of it is 2 columns, FullName and VoteCount. I want to refresh the DataGridView, for changes in my Database. How do I refresh the DatagridView without closing the form or clicking any button? Is it possible?
Here's my code :
private void President()
{
sc.Open();
cmd = new SqlCommand("SELECT (LastName + ', ' + FirstName + ' ' + MiddleName) as FullName,Vcount as VoteCount FROM TableVote WHERE Position='President'", sc);
try
{
_da = new SqlDataAdapter();
_da.SelectCommand = cmd;
DataTable _dt = new DataTable();
_da.Fill(_dt);
BindingSource bs = new BindingSource();
bs.DataSource = _dt;
PresDG.DataSource = bs;
_da.Update(_dt);
PresDG.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
PresDG.Columns["FullName"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
PresDG.Columns["VoteCount"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
PresDG.Columns["VoteCount"].Width = (100);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
sc.Close();
}
}
Upvotes: 0
Views: 873
Reputation: 1
There are two cases:
Upvotes: 0
Reputation: 4059
You can use Sql server CLR integration. Here Here
I will be posting in more details after a little reading however i hope it can give you a direction till that or you may find your solution.
UPDATE You can create a Trigger application and use that trigger application to call your method for binding gridview . Here is a good example to write an trigger and implementing it .
Upvotes: 0
Reputation: 1323
Call this function when ever you want to refresh your data.
YourGrid.DataSource = Refresh("SELECT...");
private BindingSource Refresh(string sql)
{
try
{
using (var da = new SqlDataAdapter(sql, new SqlConnection(Properties.Settings.Default.ConnectionString)) { FillLoadOption = LoadOption.Upsert })
{
da.SelectCommand.Connection.Open();
da.Fill(dataSet.YourTable);
}
}
catch(Exception ex) { MessageBox.Show(ex.Message); }
return new BindingSource(dataSet, "YourTable");
}
Upvotes: 1
Reputation: 369
Use a timer and do this
string connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
MySqlConnection conn = new MySqlConnection(connectionString);
MySqlDataAdapter adptr = new MySqlDataAdapter("Select * FROM " + tableName, conn);
DataTable tabloSql = new DataTable();
adptr.Fill(tabloSql);
dataGridView1.DataSource = tabloSql;
Note: Do this if your program doesn't make changes on your DataTable. if it makes changes on datatable when you refresh the table your changes on datatable will delete
Upvotes: 0
Reputation: 418
Does your database get update frequently? if so you can use a periodic update using a timer.
Upvotes: 0
Reputation: 21088
I think you have to re-fill the complete DataGridView.
Ways:
Upvotes: 1