Form Re-Submission Deletes Next GridView Row - c#

I have a Gridview and the OnRowDeleting method with removes a record from the database and the gridview.
My problem is that when a user click the delete button in the Gridview the record will be removed from the database but the GridView does not show this update (does not refresh). If the user then refreshes the page causing a form re-submission then the GridView deletes the row below the originally deleted row and so on if the page is refreshed again.
How can I prevent this from happening?
Here is my gridview:
<asp:GridView runat="server" ID="gvShowQuestionnaires" HeaderStyle-CssClass="table_header" CssClass="view" AlternatingRowStyle-CssClass="alt" AlternatingRowStyle-BackColor="#f3f4f8" AutoGenerateColumns="False"
DataKeyNames='QuestionnaireID' OnRowDeleting="gvShowQuestionnaires_RowDeleting" OnRowEditing="gvShowQuestionnaires_RowEdit" OnSelectedIndexChanged="gvShowQuestionnaires_SelectedIndexChanged" FooterStyle-CssClass="view_table_footer" >
<Columns>
<asp:BoundField DataField="QuestionnaireID" HeaderText="ID" HeaderStyle-Width="80px" ItemStyle-CssClass="bo"></asp:BoundField>
<asp:BoundField DataField="QuestionnaireName" HeaderText="Questionnaire Name" />
<asp:ButtonField CommandName="select" ButtonType="Link" Text="hello" />
<asp:CommandField HeaderText="Options" CausesValidation="true" ShowDeleteButton="True" ShowEditButton="true" EditText="Edit">
</asp:CommandField>
</Columns>
</asp:GridView>
Here is the OnRowDeleting method.
protected void gvShowQuestionnaires_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int questionnaireID = (int)gvShowQuestionnaires.DataKeys[Convert.ToInt32(e.RowIndex)].Value;
GetData.DeleteQuestionnaire(questionnaireID); // Deletes Questionniare from database
gvShowQuestionnaires.DataSource = DT;
gvShowQuestionnaires.DataBind();
}

You could always redirect the user to the initial page after the row was deleted, e.g. in the RowDeleted handler.
Response.Redirect(Request.RawUrl);
This should work because the delete action is a POST command to the current .aspx page.

Related

Update Gridview with data from radio button list on button click

Good Day!
I'm having a hard time with my Gridview. I'm using C#.net and sql server. I want to update my gridview rows with the data from the column of radio button list with a button outside gridview. Here's my gridview;
I want to update column[rating] with the selected value from radio button list on a single button click.
Currently, I update the gridview column rating by clicking the rate button and getting the rating value from the dropdown list above the gridview.
Now, I'm wondering if there's a way to do it on one click and get it's value from the radio button list inside the gridview. My gridview code is here;
<p>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" onrowcommand="delete_enroll"
DataSourceID="training" Width="826px" AllowPaging="True" Visible="False"
style="text-align: center">
<Columns>
<asp:ButtonField ButtonType="Button" CommandName="deleterow" Text="CANCEL" />
<asp:ButtonField ButtonType="Button" CommandName="RATE" Text="RATE" />
<asp:BoundField DataField="Training_id" HeaderText="Training_id"
SortExpression="Training_id" />
<asp:BoundField DataField="User_id" HeaderText="User_id"
SortExpression="User_id" />
<asp:BoundField DataField="User_name" HeaderText="User_name"
SortExpression="User_name" />
<asp:BoundField DataField="Date_enrolled" HeaderText="Date_enrolled"
SortExpression="Date_enrolled" />
<asp:BoundField DataField="Rating" HeaderText="Rating"
SortExpression="Rating" />
<asp:TemplateField HeaderText="Rate">
<ItemTemplate>
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem Text="Passed" Value="Passed"></asp:ListItem>
<asp:ListItem Text="Failed" Value="Failed"></asp:ListItem>
</asp:RadioButtonList>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</p>
Any help would be appreciated. Thanks!
You can loop through the rows of gridview in you button click event handler and update the respective row like this:-
protected void btnUpdate_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
RadioButtonList RadioButtonList1 = row.FindControl("RadioButto nList1")
as RadioButtonList;
row.Cells[6].Text = RadioButtonList1.SelectedValue;
}
}

Insert/Update/Delete on GridView generated by Entity Framework

I'm using EF 6.1.3 and SQL server 2014 for this ASP.NET Web Forms application. I drag&dropped a gridview on my .aspx page design view and used Smart Tag to choose my data source and automatically fill the grid. I enabled edit and delete operations on gridview and it works with no problem but I want it to use the functions I wrote.
This is what I tried for delete operation
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int rowIndex = Convert.ToInt32(e.CommandArgument);
Result<Models.UserList> result;
using (ModelOperations.UserList.IUserListOperations dao = new ModelOperations.UserList.UserListOperations())
{
result = dao.removeUser(new Models.UserList()
{
ID = Convert.ToInt32((GridView1.Rows[rowIndex].Cells[1].Text))
});
}
}
}
It actually works but the page gives an error. The method in my UserListOperations have a try-catch block but there is no exception caught because the code is simply working.
This is the GridView code generated by EF
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="UserID" DataSourceID="myEntities">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" />
<asp:BoundField DataField="UserID" HeaderText="UserID" ReadOnly="True" SortExpression="UserID" />
<asp:BoundField DataField="UserName" HeaderText="UserName" SortExpression="UserName" />
<asp:BoundField DataField="UserPW" HeaderText="UserPW" SortExpression="UserPW" />
<asp:BoundField DataField="UserType" HeaderText="UserType" SortExpression="UserType" />
</Columns>
</asp:GridView>
And this is the error
Store update, insert, or delete statement affected an unexpected
number of rows (0). Entities may have been modified or deleted since
entities were loaded. Refresh ObjectStateManager entries.
If I take the values from textbox and send values that way, there is no error so I'm guessing it's something about the auto-generated grid.

Asp.net/c# -> Gridview Pager doesn't get updated when gridview rows are filtered (or hidden)

I have the below code where I have some conditions because of which I have to hide the row from showing to end user. "ShowRow" is a boolean value that gets set in GetUnitOfMeasure function (not copied here) based on these conditions.
There are some real conditions which is forcing me to hide. I tried to include them while building data source but I have to hide it before display.
Problem I am facing is the paging is not getting refreshed based on total rows shown at the end. For example, if I have TOTAL of 200Rows in the grid and only 2 rows needs to be shown and if these 2 rows are found in paging 3, then when page is loaded it still shows paging 1 2 3 4 and 3rd page has the valid 2 rows.
Please suggest.I have also used "onDataBound" against gridview (not copied here) but I just hide some columns here.
ASPX page
<asp:GridView ID="SearchResults" runat="Server" AutoGenerateColumns="false" EnableViewState="false"
AllowPaging="true" PageSize="50" OnDataBound ="SearchResults_DataBound" OnRowDataBound="SearchResults_RowDataBound">
<RowStyle CssClass="EvenRow" />
<AlternatingRowStyle CssClass="OddRow" />
<Columns>
<asp:TemplateField meta:resourceKey="UmSellField">
<ItemStyle CssClass="alpha" />
<HeaderStyle CssClass="alpha" />
<ItemTemplate>
<asp:Label ID="UmSellLabel" runat="server" EnableViewState="false" Text='<%# GetUnitOfMeasure(Container.DataItem,false) %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
codebehind
protected void SearchResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType.Equals(DataControlRowType.DataRow))
{
e.Row.Visible = showRow;
e.Row.Cells[0].Visible = showRow;
}
}

Adding cells in GridView

How can i add cell in specific column for each row in gridview,i want to use RowCreated Events.
i have gridview that has 3 columns (ProductName, Price, Count) i get (ProductName, Price) from database, and i want to add value for (count), ex: (Kitkat, 2$ ) i want to add number 5 to (count) column, i want to handle this operation when each row created.
Thanks
Since you haven't shown your markup, I'm going to assume (based on your comment) that the first two columns are <BoundFields>. If that's the case, I would add a third column as a <TemplateField>, place a Label in it, and use the RowDataBound event to add the correct number to the Label.
Here is what the markup would look like:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowdatabound="GridView1_RowDataBound">
<Columns>
<asp:BoundField DataField="ProductName" HeaderText="Product Name" />
<asp:BoundField DataField="Price" HeaderText="Price" />
<asp:TemplateField HeaderText="Count">
<ItemTemplate>
<asp:Label ID="countLbl" runat="server"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And the code-behind:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
Label countLbl = (Label)e.Row.FindControl("countLbl");
//Your logic for what number to use should go here, I'm just defaulting to 5.
countLbl.Text = "5";
}

Checked checkbox in gridview, in c# codebehind checked property is false

I have custom upload control. The control has gridview with the uploaded documents and the first column has checkbox for selecting documents I want to delete by clicking Delete button. The upload control is contained in other UserControls almost everywhere in the application and works properly, except at one control. The problem is when I check some document for deleting, when the code executes the checked property of the checkbox is false.
<asp:GridView ID="gvFiles" runat="server" AutoGenerateColumns="false" ShowHeader="true"
CssClass="DataGrid" Width="100%" OnRowDataBound="gvFiles_RowDataBound">
<HeaderStyle HorizontalAlign="left" CssClass="UploadControlGridHeader" />
<RowStyle CssClass="dlcell" />
<EditRowStyle CssClass="dlsell" />
<Columns>
<asp:TemplateField HeaderText="Delete">
<ItemStyle Width="8%" HorizontalAlign="Center" />
<ItemTemplate>
<asp:CheckBox ID="chkFile" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and this is the delete button event
protected void btnDelete_Click(object sender, EventArgs e)
{
for (int i = 0; i < gvFiles.Rows.Count; i++)
{
CheckBox chk = (CheckBox)gvFiles.Rows[i].Cells[0].FindControl("chkFile");
if (chk.Checked)
{
// If file is marked/checked to be deleted
// then delete it.
DeleteFile(i);
}
}
Session[KEY_VIEWSTATEFILES] = this.FileList;
// Repopulate gridview
BindToGridView();
// Call command to keep same visible screen.
CustomCommandEventArgs command = new CustomCommandEventArgs(COMMAND_FILE_DELETED, null);
OnHappyCommand(command);
}
Not having your DeleteFile(i) code, I can't be sure, but I will take a guess that into that function you remove/delete the row. Am I right? If yes, then it change the index of all your rows, which make you think it is not checked when you check the row that you remember to have checked. You will have to use a backward for loop to fix this.

Categories