GridView to add Delete column dynamically (Server Side) - c#

We read from XML and create columns in asp gridview. Also same XML is used to create columns in a data table. We populate that data table with desired data and bind data table to gridview using server side code.
Now, we want to add delete link in each gridview row and not sure how to manage it. Since we are not using RowDataBound method.
Any help?

Lot of solution exists for this problem.
Example the delete the row from the datasource (DataSource.RemoveCurrent).
If you can define the "delete button row" (type button) you can use a simple dataGridView1.Rows.Remove .
Or if you want to delete the row with a simple click on the button:
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) {
if (e.ColumnIndex == 8)// define the delete button column
{
dataGridView1.Rows.Remove(dataGridView1.Rows[e.RowIndex]); // delete with index!
} }

Related

Sorting by Column Header Click Removes Column Filters

I have a gridview table that has auto generated columns and the rows in those columns can be sorted by clicking the column name since I have "AllowSorting" on. I also have checkbox lists that the user can check or uncheck to filter columns in and out of the table.
The problem is when the user filters the table to whatever columns they want and then they click on any column name, it will sort by that column but it brings back all of the columns that they filtered out.
I am guessing that I might need to create a method with GridViewSortEventArgs or DataGridViewCellMouseEventArgs but when I have protected void method(object sender, DataGridViewCellMouseEventArgs e) it gives me the error "The type or namespace name could not be found but GridViewSortEventArgs will not return an error like that. I'm basically thinking I should try to make it when you click on the column headers to do almost the same exact thing as when you click the search button after you select what columns you want in the table so it will run the query with the filtered columns instead of basically selecting * columns and then sorting.
How do I go about this?

How to update db according to the changes of C# DataGridView?

I have a DataGridView and a save button on one of my forms. Users can edit the data in the gridview (data comes from a database) and I want to update the database on save button clicking with the user edited data. How can I do it?
On your Save Button click event
private void SaveButton_Click(object sender, EventArgs e)
{
System.Data.DataTable dsnew = ((DataView)gridView1.DataSource).Table;
}
This will get your gridview into dataset
Once you get data in your dataset you can perform your necessary Update or Insert Query
Also, remember to terminate any current edit that the user is doing.
gridView1.EndEdit();
((DataRowView)gridView1.CurrentRow.DataBoundItem).EndEdit();
The first line is usually enough, but when you have the DataGridView object bound to a DataView, you need the second line to force the underlying DataTable to update.

CRUD operations in Datagridview bound to SQL Database

I have a problem with adding a new row to my datagridview. I want it to be done by Add button. I based my binding on this tutorial http://msdn.microsoft.com/en-us/library/fbk67b6z.aspx so my code looks almost exactly the same. Is it possible to: first - add a new row to datagridviews bound datasource and then update the database by clicking update button? I managed to get clone of selected row which will be used as a template for the new row. Thanks for your help.
Well, I'm not able do something like that
dataGridView1.Rows.Add(selected_row); It throws an exception. And I
don't know how to insert a row in my database. – user1651521 1 hour
ago
You can't add rows directly to the datagrid for a grid that is databound. You have to add the new row to the bound table.
So if you are using the same code as that example, you would add a new record to the DataTable that is the datasource of your bindingsource object. So something like this:
private void addButton_Click(object sender, System.EventArgs e)
{
//I'm assuming your datatable is a member level variable
//otherwise you could get it through the grid
//have the datatable send you back a new row
DataRow newRow = table.NewRow();
//populate your new row with default data here
//....
//add the new row to the data table
table.Rows.Add(newRow);
}
What you could use is the OnRowsAdded event of your DataGridView. Here's a link to this event: http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.onrowsadded.aspx. In this event, you could then iterate through each row added and insert them in your database with an Insert statement. I never used that event, but it looks like what you need.
EDIT: I just saw this in your example.
private void submitButton_Click(object sender, System.EventArgs e)
{
// Update the database with the user's changes.
dataAdapter.Update((DataTable)bindingSource1.DataSource);
}
If you have the EditMode activated for your DataGridView and a submit button, wouldn't this work? You must have access to your SqlDataAdapter, so declare it as a global variable and you would be able to use it in your click event of your submit button.

How to delete a row in a gridview and the underlying datasource without using a SqlDataSource, ObjectDataSource, etc

I have a GridView which I am populating by calling a method to return a datatable with two columns. After I return the datatable, I bind it to the gridview and display it.
I am not using a SqlDataSource or an ObjectDataSource, so what is the proper way to Delete a row from the gridview and the underlying data in the database. I just need to delete from one table which is called portfolio. It has 3 columns, ID, which is the unique key, PortfolioID, and PortfolioName. The datatable returns the PortfolioName and the number of items in the Portfolio. I was thinking I could do this in the Row_Deleting event where I would do something like:
DELETE * FROM Portfolio WHERE PortfolioID = #PortfolioID
Am I on the right track and how would I do this? Could I bind the PortfolioID to the GridView DataKey property (What is the correct syntax to do this?)
I assume that you're deleting a row on a button press. If so, I usually do something like this:
<asp:GridView ID="myGrid" runat="server" DataKeyNames='PortfolioID' OnRowCommand="dgStudent_RowCommand">
<Columns>
<asp:ButtonField ButtonType="Button" CommandName="Delete" Text="Delete"></asp:ButtonField>
</Columns>
</asp:GridView>
Then in your code-behind:
protected void myGrid_RowCommand(object sender, GridViewCommandEventArgs e)
{
// create and open DB connection
int PortfolioID = (int)myGrid.DataKeys[Convert.ToInt32(e.CommandArgument)].Value;
DeleteRow(PortfolioID); // your implementation
myGrid.DataBind();
}
DeleteRow is your implementation of the row delete (maybe the SQL you have above). myGrid is your grid. PortfolioID is the primary key. This also assumes that the only button in your grid is the delete button. If you have more than one button, you'll need to check e.CommandName=="Delete" to make sure you get the delete button.
I would probably abstract the DB call further out than there. I would probably process the rows after row changes were complete. For postprocessing you can check the rowstate to determine what to do with the data in the row.
As i understood you want to delete an row from datagrid view that is filed from database table. This means you want to delete and Table record from some database.
The best way to do this is to put an textbox somewhere and creat an event for your datagridview ( on Row select event). This way when you will selct the row you want to delete the id of that roow will be sent to the textbox ( this will be coded). After you have the id of the row you want to delete just add one more button to delete the record in database and bind the datagridview once again.
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
this.txt_portfolioId.Text=dataGridView1.CurrentRow.Cells["portfolioID"].Value.ToString();
}
private void btn_Delete(object sender, EventArgs e)
{
//You need to connect to database(regular database connection this connection string and sqlcommand and add this sqlquerry:
Delete * from yourtable where portfolioid = '"+Convert.ToInt32(this.portfolioId.Text)+"';
}

Working with the "onclick" of a server side dynamically created TableRow

I am dynamically creating a table which I want to have clickable rows. When the user clicks on one of the rows I want to redirect to a page specific to the item of that row. My question is how on the server side can I wire the "onclick" event to a routine that will then allow me to build a url based on some of the data included in the row they clicked?
for example I would want to do this on click:
Response.Redirect("SomePage.aspx?" itemType + "&" + COLUMN1VALUE);
where COLUMN1VALUE would be the first column in the row that was clicked.
It sounds like your actual goal is simply to display/edit the row on another page. If this is the case, you could simply add a javascript event handler to the table row when you create it.
<tr onclick="window.location='DetailPage.aspx?id=<%= IdFromDb %>'">
<!-- etc......-->
</tr>
If you use a GridView to create the table you can inject this in the RowDataBound event:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
string OnClickCmd = "window.location='DetailPage.aspx?id=";
if (e.Row.RowType == DataControlRowType.DataRow)
{
OnClickCmd += DataBinder.Eval(e.Row.DataItem, "IdFromDb").ToString() + "'";
e.Row.Attributes.Add("onclick", OnClickCmd);
}
}
Unless you need to do something in the postback, there is no need to redirect. Further, you could just create a hyperlink when you create the row eliminating the need for javascript, you don't need the full row clicking experience.
I would build the link in the table as an actual anchor tag to your SomePage.aspx (while you're building your table, you should know what the query string would be for each table row), opposed to a server side control that redirects on postback
In your click event handler, you cast the sender as button, then get its parents until you get to the TableRow, then do a FindControl() to find the control with the value specific to that row and use it to build your URL!
Good luck!

Categories

Resources