Add selected rows from one GridView to another GridView - c#

I need to add the selected rows from one GridView to another GridView in ASP.NET C#.
So the code i was implemented on my project to copy selected rows from one Grid to another Grid.
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection sc = new SqlConnection(#"Data Source=.\sqlexpress;Initial Catalog=x;Integrated Security=True");
sc.Open();
SqlDataAdapter sd = new SqlDataAdapter("select * from BookDetails", sc);
DataSet ds = new DataSet();
sd.Fill(ds, "BookDetails");
sc.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
}
protected void GridView1_SelectedIndexChanged1(object sender, EventArgs e)
{
GridViewRow row = GridView1.SelectedRow;
GridView2.DataSource = row; //error here
GridView2.DataBind();
}
when i run the project i got an error (GridView2.DataSource = row;) :-
"Data source is an invalid type. It must be either an IListSource, IEnumerable, or IDataSource."
Image of what i need to implement
error of the code

Have you tried typecasting "row" to be "IListSource, IEnumerable, or IDataSource."? If that doesnt work, it may be because GridView2.DataSource can only be IListSource, IEnumerable, or IDataSource thus meaning it simply isn't possible. I don't fully understand what you're trying to do in the function "GridView1_SelectedIndexChanged1".

Related

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.

Both DataSource and DataSourceID are defined on 'GridView2'. Remove one definition

I am trying to reload a gridview upon date selected from calendar.
I know there are duplicate questions on SO but their answers did not work for me
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
Label1.Text = Calendar1.SelectedDate.ToShortDateString();
DataSet ds = dlObj.FillDataSet("SELECT top 5 [DName], [bloodGroup], [dateDonated] FROM [tblDonors] ORDER BY [dateDonated] DESC ", "tblDonors");
GridView2.DataSource = ds;
GridView2.DataBind();
}
And the method FillDataSet() is this
public DataSet FillDataSet(string q, string tableName)
{
DataSet ds = new DataSet();
try
{
SqlDataAdapter da = new SqlDataAdapter(q, thisConnection);
da.Fill(ds, tableName);
return ds;
}
catch (Exception)
{
return ds;
}
}
When I click any date, this error occurs
Both DataSource and DataSourceID are defined on 'GridView2'. Remove one definition.
DataSourceID="ds"
This is not needed when you are adding datasource from code behind.
While, in general, you should really decide on whether to use design side datasource or use code behind, there may be occasions where it is preferable to use both. One way to cheat a bit, in code behind use:
grid.DataSourceID = null;
grid.DataSource = dataTable;
grid.DataBind();
In Calendar1_SelectionChanged you should simply call
GridView2.DataBind()
and handle whatever it is you are trying to do in the
DataSourceID_Selecting
event by updating e.Result

Display tables from SQL in DataGridView

I created a DataBase named charityah containing 5 tables. Their names are listed in a combobox.
When I choose one of them I want to display their content in a DataGridView.
What I tried is: first I linked the DataGridView to this database and tried this code that I found:
SqlConnection connection = new SqlConnection();
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string s = comboBox1.Text;
connection.ConnectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\Downloads\charityah.mdf;Integrated Security=True";
using (connection)
{
connection.Open();
SqlDataAdapter adapter = new SqlDataAdapter("select * from "+s, connection);
DataSet ds = new DataSet();
adapter.Fill(ds, s);
dataGridView1.DataSource = ds.Tables[0];
dataGridView1.Refresh();
}
}
This method doesn't give me any errors and it finds the tables, but nothing is seen in the DataGridView.
Since you report (comments) that there are rows, it sounds like the primary problem (connection disposal aside) is an issue with data-binding. A few thoughts leap to mind:
is the table in virtual mode?
is it adding columns?
do the columns already exist?
You might want to try adding:
dataGridView1.VirtualMode = false;
dataGridView1.Columns.Clear();
dataGridView1.AutoGenerateColumns = true;
before the:
dataGridView1.DataSource = ds.Tables[0];
You might also want to check that dataGridView1.DataMember doesn't have a value assigned.
try this, some times nonsense items do create a lot of mess. so try setting autogenerate columns to true. may this starts showing you the results. because as per your comments, it dosent seems there could be any other issue. so just give it a try
dataGridView1.AutoGenerateColumns = true;

Refresh GridView After Data is Deleted From DetailView Using 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
}

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();
}

Categories

Resources