Refresh GridView After Data is Deleted From DetailView Using C# - c#

When user select any record from the GridView then my DetailView is updated based on the selection of the GridView. So what I am trying to do is that when I delete anything from the DetailView then I want to refresh the GridView so basically I don’t want to show still the deleted record in the GridView. I have tried to resolve this issue by doing the data bind after my connection and SQL statement but it does not refresh it. One thing to note is that I am using a Accordion pane but both my gridview and the detailview are on the same pane. I am not sure if this is breaking anything. Here is my code:
protected void Refresh_ItemCommand(object sender, DetailsViewCommandEventArgs e)
{
if (e.CommandName.Equals("Delete", StringComparison.CurrentCultureIgnoreCase))
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("select ID, Name, Address from dbo.MyTable", con);
DataTable dt = new DataTable();
da.Fill(dt);
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
}

You may use the event of the Data view called "ItemDeleted" as follows:
DetailViewName_ItemDeleted(object sender,
DetailsViewDeletedEventArgs e)
{
// Refresh the GridView control after a new record is updated
// in the DetailsView control.
GridViewName.DataBind();
}
The above code is from the official MSDN site for detail view control.
The other way (which I prefer) is to handle the data grid during the Page_load procedure so when you press your delete button in the detail view, the page will perform a postback.
So in the procedure Page_load you can call another procedure which fills the data grid. The code might be like this:
if (isPostback)
{
FillGrid();
}
private void FillGrid()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("select ID, Name, Address from dbo.MyTable", con);
DataTable dt = new DataTable();
da.Fill(dt);
Gridview1.DataSource = dt;
Gridview1.DataBind();
}

Your code doesn't show anything where the record is actually deleted so it's understandable that when you re-fetch the data still contains everything.
What you need to do is:
Execute a sql statement to delete the record
Re-fetch the data
Rebind the data.
If you follow those 3 steps it will work.

try to use the event that is called in case of pressing the delete key from the DGV
private void DGV_DeleteKeyPressed(object sender, KeyEventArgs e)
{
//enter code here
}

Related

Refresh datagridview from another user control

Using C# and Winform.
I read a couple of similar questions but couldn't find any great answers that could interlock with my code. So, bear with me and thank you in advance for helping me.
I have a single form that contains multiple User Controls. Inside the first user control, you can insert, update and delete records from the database. In the second User Control, there is a datagridview that is populated with all records.
The problem I have is that whenever I insert, update or delete a record inside the first user control. It won't refresh inside the datagridview when I swap to the second user control.
Beneath is the second user control that populates the datagridview
private void populate()
{
database.OpenConnection();
string query = "SELECT id, name, qoute, time, date from maintable";
SQLiteDataAdapter sda = new SQLiteDataAdapter(query, database.connection);
SQLiteCommandBuilder builder = new SQLiteCommandBuilder(sda);
var ds = new DataSet();
sda.Fill(ds);
dtgNav.DataSource = ds.Tables[0];
databas.CloseConnection();
}
private void Navigation_Load(object sender, EventArgs e)
{
populate();
dtgNav.Columns[0].HeaderText = "ID";
}
public void Refresh()
{
this.Refresh();
}
Beneath is the code for adding a record to the datagridview in the first user control
private void btnAdd_Click(object sender, EventArgs e)
{
database.OpenConnection();
string query = "INSERT INTO maintable (`id`, `name`, `qoute`, `time`,`date`) VALUES (#Id, #Name, #Qoute, #Time, #Date)";
SQLiteCommand command = new SQLiteCommand(query, database.connection);
command.Parameters.AddWithValue("#Id", tbxID.Text);
command.Parameters.AddWithValue("#Name", tbxName.Text.Trim());
command.Parameters.AddWithValue("#Qoute", tbxQoute.Text.Trim());
command.Parameters.AddWithValue("#Time", tbxTime.Text.Trim());
command.Parameters.AddWithValue("#Date", dtpDate.Value.ToString("yyyy-MM-dd"));
command.ExecuteNonQuery();
MessageBox.Show("Added new event into the database.");
database.CloseConnection();
usercontrol2.Refresh();
}
I would appreciate it if we found a way to refresh the datagridview when the button is clicked without changing the original code all too much.
You have a public void Refresh method in the second usercontrol, try modifying this.Refresh();, to say populate();. this should call your private void populate method that you called when loading which should reload the grid. Let me know if this helps.

Changes to DataGridView aren't being reflected in database

I have a DataGridView control and a save button. When the Save button is clicked, I want any changes made to the DataGridView to be reflected in my database via a DataAdapter Update() command. However, after hitting the save button and reloading the form, the updates are not there.
Here is all the code for the Save button currently:
private void btnSave_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=addtool.database.windows.net;Initial Catalog=AddToolToInventoryDB;User id=kanerbw; Password=Rabaraba!11;");
DataTable dt = new DataTable();
SqlDataAdapter adapter = new SqlDataAdapter("select * from ToolTB", con);
SqlCommandBuilder myBuilder = new SqlCommandBuilder(adapter);
con.Open();
SqlCommandBuilder scb = new SqlCommandBuilder(adapter);
myBuilder.GetUpdateCommand();
adapter.UpdateCommand = myBuilder.GetUpdateCommand();
adapter.Update(dt);
con.Close();
}
EDIT: I had forgotten to set the datasource of my DGV to the datatable. Here's the working code:
private void btnSave_Click(object sender, EventArgs e)
{
using (var con = new SqlConnection(connectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter("select * from ToolTB", con);
SqlCommandBuilder myBuilder = new SqlCommandBuilder(adapter);
dgvProductInfo.DataSource = dt;
adapter.UpdateCommand = myBuilder.GetUpdateCommand();
adapter.Update(dt);
dt.Clear();
adapter.Fill(dt);
}
}
Your code has several problems:
You are not enclosing the SQLConnection in a using statement. You should always use this pattern so that the connection is properly disposed: using(var connection = new SqlConnection(...)){ rest of statements here }
On the btnSave_Click function, you are getting the data again from the database -see the select * from tbl... code- and you are populating the DataTable again; therefore, it's obvious that there won't be any changes reflected. What you need to do instead is read the Updated DataTable from the page and use it inside the btnSave_Click function to push the updates to the database.
Your question refers to DataGridView which I believe is a User Control on WinForms, but your question is tagged as ASP.NET. Are you referring to a GridView control instead? Either way, both controls should have a way of getting the DataSource bound to them. You should be able to use that DataSource to push the updates to the database.
I hope this pointers are helpful. I cannot be more specific given the code you provided in your question.

Editing contents of a listbox that is populated by a sql query datasource using c#

I have a list box that is populated by a query result set, i would to give the user the ability to edit the contents of the list box, and update the database back end, how can i achieve this?
public Brand_Manager(Main parent)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["SqlConn"].ConnectionString.ToString());
SqlCommand cmd = new SqlCommand("select Brand_ID, Brand_Name from Brand where status=1", conn);
conn.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable t = new DataTable();
da.Fill(t);
listBox1.DisplayMember = "Brand_Name";
listBox1.DataSource = t;
listBox1.ValueMember = "Brand_ID";
conn.Close();
}
private void Edit_Button_Click(object sender, EventArgs e)
{
this.Edit_Button.Enabled = false;
object item = listBox1.SelectedItem;
Edit_Brand frm = new Edit_Brand();
this.AddOwnedForm(frm);
frm.ShowDialog();
}
Do you use WPF or WinForms? Anyway you need to investigate Bindings: BindingSource in WinForms or Binding class in WPF (http://msdn.microsoft.com/en-us/library/ms750612.aspx).
Look at DataTable events http://msdn.microsoft.com/en-us/library/system.data.datatable_events.aspx . There is RowChangedEvent. Call update sql command in its handler.
You need to use datagridview for this purpose. It is designed for this purpose. You can assign the datasource to gridview and allow user to edit rows. Then by handling row edited event or by giving the button you can update the database. See an example here

ASP.NET why Gridview Paging on page 2 and the rest of it are disappear?

I have so many list of ServerName in GridView, so I decide to add paging. The data show list result on page 1 but on page 2 and the rest of it is not display anything. I already have OnPageIndexChanging="GridViewServer_PageIndexChanging" in GridViewServer property. Please help! Here is c# code behind,
protected void GridViewServer_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridViewServer.PageIndex = e.NewPageIndex;
GridViewServer.DataBind();
}
A GridView binding function codes,
public void BindGridView()
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Database_Shared_NotebookConnectionString"].ConnectionString);
conn.Open();
string sqlquery = ("SELECT * FROM tblServer");
SqlCommand command = new SqlCommand(sqlquery, conn);
SqlDataAdapter adp = new SqlDataAdapter(command);
DataSet ds = new DataSet();
adp.Fill(ds);
GridViewServer.DataSource = ds.Tables[0];
GridViewServer.DataBind();
}
You need to set your GridView's datasource appropriately. You can't just call DataBind if the datasource isn't properly set. Basically what it amounts to is binding your GridView to null (which would have no page 2). I would recommend having a private method that is responsible for this process and whenever you need to bind you call that.
private void BindGridViewServer()
{
GridViewServer.DataSource = GetYourData(); // This should get the data
GridViewServer.DataBind();
}
Call this method from within your event with:
protected void GridViewServer_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridViewServer.PageIndex = e.NewPageIndex;
BindGridViewServer();
}
This could be made more extensible by passing in the GridView as a parameter, but you'd have to have other parameters as well to make sure the method retrieves the proper data.
Here's a very good tutorial (with sample code) on custom GridView paging. This makes the paging controls look like the familiar ones you see on a lot of search engines, forums, etc.
http://geekswithblogs.net/aghausman/archive/2009/05/18/custom-paging-in-grid-view.aspx
You have to give datasource to GridViewServer every time on page index changed.
so the code would be like this
protected void GridViewServer_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridViewServer.PageIndex = e.NewPageIndex;
GridViewServer.Datasource = MethodReturningDataTable();
GridViewServer.DataBind();
}

gridview databinding problem

i am using asp.net with c#
and i want to bind my data to the gridview
i have success fully done that by wizard
but now it is show me this error
protected void Button1_Click(object sender, EventArgs e)
{
SqlDataAdapter dbadapter = null;
DataSet dbdata = new DataSet();
using (SqlConnection dbconn = new SqlConnection("Server=CJ\\SQLEXPRESS;Database=elligiblity;User ID=sa;Password=123;Trusted_Connection=False;"))
{
dbadapter = new SqlDataAdapter("select * from Main_Table", dbconn);
dbadapter.Fill(dbdata);
}
GridView1.DataSource = dbdata;
GridView1.DataBind();
}
i am getting this error
Both DataSource and DataSourceID are defined on 'GridView1'. Remove one definition
You cannot specify custom binding from code if gridview is already binded to a datasource. Either remove DataSourceID in gridview properties from your aspx page or change the select command of the sql datasource to which it is binded from code like,
protected void Button1_Click(object sender, EventArgs e)
{
sdsFtrtDet.SelectParameters.Clear(); // Clear any innitial parameters of your sql datasource which is binded with gridview
sdsFtrtDet.SelectCommand = "select * from tableA"; //Specify new query
sdsFtrtDet.DataBind(); // Data Bind
}
Cheers.
Edit
You probably are not seeing your gridview because you would have used template fields binded with datasource ? You can use another gridview to bind with your 2nd query. Leave the 1st gridview as it is so you wont get in trouble with template fields.
Cheers.
So that means that in your markup, you're specifying a value for DataSourceID, but then in the code you've shown, you're setting DataSource. DataSourceID and DataSource are mutually exclusive.

Categories

Resources