I'm trying to create a refresh button to automatically refresh the data inside my datagridview after i have finish updating them.
However, my refresh button doesn't seem to work. The data displayed remains the same as the original one. It only gets updated after i manually end my windows app and rebuild it.
Here is my code:
private void button_refresh_Click(object sender, EventArgs e)
{
this.acuzioSecureStore_DatabaseXDataSet.AcceptChanges();
}
Please assist. thanks ^_^
The easiest way to handle this is to use a Binding Source object.
If your loading information into your DataGridView from an Access Database then your most likely storing the Data in a Dataset or DataTable.
Create a Binding Source object, and once you have populated your DataTable/Dataset, set the datasource for your Binding Source to your DataTable. Then set the Datasource from the DataGridView as the Binding Source object.
Doing this ensures that any changes in your datagridview or reflected in the DataTable and vice Versa. If you reload data into your DataTable it will reflect in the Data Grid Automatically.
DataTable dt = new DataTable();
BindingSource bs = new BindingSource();
bs.DataSource = dt;
dataGridView1.DataSource= bs;
All changes will now happen automatically.
Hey the solution above is good but when the above code is executed,the table disappears and is not seen. And if I execute
da.Fill(ds, "p");
dataGridView1.DataSource = ds.Tables["p"];
then whole table is created again.
private void button_refresh_Click(object sender, EventArgs e)
{
SqlConnection con=new SqlConnection(#"");
string query="select * from abc";
SqlCommand cmd=new SqlCommand(query,con);
SqlDataAdapter da=new SqlDataadapter(cmd);
DataTable dt=new DataTable();
da.Fill(dt);
dataGridView1.DataSource=dt;
}
I had a datagridview, bound to a table in an Entity Framework database:
dataGridView1.DataSource = MyDatabase.MyTable;
It would never refresh despite two wasted days.
I solved it with a simple workaround:
private void button_refresh_Click(object sender, EventArgs e) {
dataGridView1.DataSource = MyDatabase.MyTable.Where(i =>(true));
}
This is an ugly workaround, and friend explained me how it works - if I do just dataGridView1.DataSource = database.table, it will cache the table and use the cached data forever. The fact that each time we create a new dummy query, prevents .net from caching it.
Please try this, it worked for me and let me know if you have any better option.
private void button3_Click(object sender, EventArgs e)
{
dataGridView1.Refresh();
}
you Can Bind dataGridView On PageLoad or UserControl Load Event and After chage in grid view Call the Load Event
like
this.ucUsers_Load(null, null); // Windows From C#
Related
id pojam opis id pojam opis(duplicate columns)
I am just testing connection from db to c#, and instead of columns id pojam opis I am actually getting id pojam opis id pojam opis in datagridview in c#. Here is part of code which I use to connect database to c#:
public partial class Form1 : Form
{
BindingSource bindingSource1 = new BindingSource();
MySqlConnection conn = new MySqlConnection("Data Source=localhost;database=test;user=root;password=;");
public Form1()
{
this.Load += new System.EventHandler(Form1_Load);
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = bindingSource1;
ubaciPodatke();
}
public void ubaciPodatke()
{
try
{
MySqlDataAdapter da = new MySqlDataAdapter("SELECT * FROM csharp", conn);
DataTable table = new DataTable();
da.Fill(table);
bindingSource1.DataSource = table; dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Is it my mistake, or It has to do something with phpmyadmin: Version information: 4.7.0-rc1. I was thinking it can happen because this version isnt stable yet?
edit: what do You think if I delete this form.resx file
user added rows, would this solve the problem?
Few things:
There is no need to do the data binding in the Load event. You can just do it in the constructor after the InitializeComponent() call. This is irrelevant to your issue.
I don't know what ubaciPodatke means since I don't speak that language, but hopefully it is equivalent of InitializeGrid(). In that case you should put
dataGridView.DataSource = null;
dataGridView.Rows.Clear();
dataGridView.Columns.Clear();
as the first line after try. I do such "clean initialize" since I sometimes design the Grid in designer, for "documentation & visualization" purposes, but do the actual grid from the code. Also, it keeps the InitializeGrid() reusable, to be called from other places.
Also, related to the question in the comments,
Am I reading data from dgv wrong?
You should read the data from the bound DataTable and not directly from the DataGridView when binding.
Solution: I had to comment some lines link1 in form.designer.cs and problem disappeared as shown in this photo link2. I am still curious why this happened as I remember only dragging dgv from toolbox and not adding manually column names.
I have a DataGridView populated with a DataSet from my Database. I am trying to make changes in the DataGridView and apply those changes to the Database whenever I press 'Enter'.
Iv read alot of this same question, and researched the topic, but am still having trouble figuring out why I cannot apply changes made in my DataGridView to my Database. (I know this has been asked before, but still cant figure this out).
Can anyone show me what im doing wrong?
DataSet ds = new DataSet();
string constring = System.Configuration.ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
SqlDataAdapter da;
public ListForm()
{
//Setting up DataGridView with data.
InitializeComponent();
da = new SqlDataAdapter("Select * from Contact_List", constring);
SqlCommandBuilder cmb = new SqlCommandBuilder(da);
da.UpdateCommand = cmb.GetUpdateCommand();
da.Fill(ds, "Contact_List");
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Contact_List";
}
//Trying to update database with DataAdapter
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
using (SqlConnection con = new SqlConnection(constring))
{
con.Open();
//I believe that the changes to the database should be applied here
//Buts its not working
da.Update(ds, "Contact_List",);
ds.AcceptChanges();
con.Close();
}
}
You should end current edit before trying to save changes:
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
var cm = dataGridView1.BindingContext[ds, "Contact_List"];
cm.EndCurrentEdit();
da.Update(ds, "Contact_List");
}
Some other notes
You don't need a DataSet. A DataTable is enough.
When you create a SqlCommandBuilder by passing a SqlDataAdapter to the constructor, all insert, update and delete commands will be generated automatically and you don;t need to do anything yourself, so GetUpdateCommand() is not necessary.
Calling EndCurrentEdit cause the changes which you made on an IEditableObject be saved to underlying data source. DataRowView which is the object behind rows of grid is an IEditableObject and you should call EndCurrentEdit of the currency manager which cause EndEdit of DataRowView be called and commits changes to the underlying DataRow and ends the editing session.
If you bind the grid to a BindingSource, calling EndEdit of BindingSource will do the same.
After saving data, you don't need to call AcceptChanges manually.
You need to add exception handling to code.
it's because you're using SqlCommandBuilder, I haven't used it in a long time and I'm looking for more info, but I believe you can only update one table, no joins, and there has to be a unique key defined, otherwise you may want to generate your UPDATE statement manually.
reference
I want to bind the DataGridView to a Table in my Database. I've found several topics about this, but I can't get it to work. Perhaps I'm missing something.
I'm building a "monitor" in which I want to see any Database changes of a specific table. So, after loading the data into a DataGridView, any change in that specific table should be propagate to the DataGridView.
Look what I've done:
SqlDataAdapter daTab;
DataTable dTable;
private void button1_Click(object sender, EventArgs e)
{
string s;
s = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\tempDB\Database1.mdf;Integrated Security=True";
SqlConnection conn= new SqlConnection(s);
conn.Open();
daTab = new SqlDataAdapter("Select * From tab", conn);
dTable = new DataTable();
daTab.Fill(dTable);
BindingSource bSource = new BindingSource();
bSource.DataSource = dTable;
dgv1.DataSource = bSource;
}
But it only updates the DataViewGrid when I run
daTab.Fill(dTable);
So I may have two options from here: 1) get it to work right (this is why I'm needing your help) or 2) put a timer and run daTab.Fill(dTable); at some time interval. I am particullary looking after option 1). So, I'd appreciate any help given.
It sounds like you're using SQL Server. If so, have a look at the SqlDependency class. You can create a delegate for this class's OnChange event and be notified of changes, which you can then propagate to your GridView. Here is a good writeup on the topic with some examples:
https://msdn.microsoft.com/en-us/library/62xk7953(v=vs.110).aspx
I have created a DataGrid and I take the data from database and put it in there.All the data retrieval are done by dynamically in the code behind.Here is a some portion of my code.
SqlConnection con = new SqlConnection("Data Source=PUNUTHL\\SQL;Initial Catalog=mytest;Integrated Security=True");
SqlDataAdapter ad;
DataSet ds = new DataSet();
static DataTable dt = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ad = new SqlDataAdapter("Select * from product",con);
ad.Fill(ds);
dt = ds.Tables[0];
DataGrid1.DataSource = dt;
DataGrid1.DataBind();
}
}
Upto this point it works perfectly.
But I wanted to add the edit function for that DataGrid
But according to my query I took the "product_ID" values as well which can not allows to be updated.
Since I use both "Etid" and "Delete" commands, "prodcut-id" may be my 3rd column as shown in the picture.
So I wanted to be that column read only when the client hit on the edit button.So how can I tackle this problem.Are there any way to get the column names or column indexed?Please can some one help me.
This is one of the way to make a column at any index readonly.
DT.Columns(0).ReadOnly = True '// Make the column(0) readonly and assign to DataGrid.
Datagrid!.DataSource = DT
where DT is datatable used to collect the data from database and is datasource to the datagrid Datagrid1.
For further editing make the column readonly= false and make changes and again turn it into readonly.
Here in your case you can make your Id column that is 2 as readonly
I am having a problem updating a datatable that is bound to a datagrid. Tried a bunch of approaches but the problem is the underlying datatable reverts back to its initial state everytime u click a command.
Here's the example code:
On Label Click:
protected void OnUserDataGridCommand(object source, DataGridCommandEventArgs e)
{
DataTable dt = DataGridUsers.DataSource as DataTable;
if (e.CommandName == "Lock Out")
{
// Approach 1
e.Item.Cells[0].Text = "Lock";
DataGridUsers.DataSource = dt;
DataGridUsers.DataBind();
// Approach 2
dt.Rows[e.Item.ItemIndex]["FirstName"] = "LOCK";
dt.Rows[e.Item.ItemIndex].AcceptChanges();
DataGridUsers.DataSource = dt;
DataGridUsers.DataBind();
}
}
So this will update the row's first name to say Lock but when you click on another row the previously Locked will revert to the first name. When I breakpoint regardless of a row displaying lock, the datatable always is the initial data (no "LOCK" data).
This line typically doesn't work for me
DataTable dt = DataGridUsers.DataSource as DataTable;
You might want to instead manage the DataSource in the session, by retrieving it out of session doing your modifications and then rebind it to the Grid.
You might also want to take a look at where the DataSource got bound to the grid the first time. Is is it running on the postback thus overwriting your changes.