This is my .cs code :
protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
Gridview1.DeleteRow(e.RowIndex);
Gridview1.DataBind();
}
and this is markup,
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true"
AutoGenerateColumns="false" OnRowDeleting="Gridview1_RowDeleting">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="Column Name">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<%-- <asp:TemplateField HeaderText="Header 2">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>--%>
<asp:TemplateField HeaderText="Data Type">
<ItemTemplate>
<asp:DropDownList ID="ddldatatype" runat="server">
<asp:ListItem>varchar</asp:ListItem>
<asp:ListItem>int</asp:ListItem>
<asp:ListItem>numeric</asp:ListItem>
<asp:ListItem>uniqueidentifier</asp:ListItem>
<asp:ListItem>char</asp:ListItem>
</asp:DropDownList>
</ItemTemplate>
<FooterStyle HorizontalAlign="Right" />
<FooterTemplate>
<asp:Button ID="ButtonAdd" runat="server" Text="Add New Row" OnClick="ButtonAdd_Click"/>
<asp:Button ID="ButtonDel" runat="server" Text="Delete Row" OnClick="ButtonDel_Click" />
<input type="hidden" runat="server" value="0" id="hiddencount" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="lnkdelete" runat="server" CommandName="Delete" >Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:gridview>
Please sugegest me. I have done this much.. but still not deleting row...
protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//Gridview1.DeleteRow((int)Gridview1.DataKeys[e.RowIndex].Value);
//Gridview1.DeleteRow(e.RowIndex);
//Gridview1.DataBind();
foreach(DataRow dr in dt.Rows)
{
dt.Rows.Remove(dr);
dt.Rows[e.RowIndex].Delete();
}
Gridview1.DeleteRow(e.RowIndex);
// dt = (DataTable)Gridview1.DataSource;
Gridview1.DataSource = dt;
Gridview1.DataBind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
GridViewRow row = (GridViewRow)GridView1.Rows[e.RowIndex];
SqlCommand cmd = new SqlCommand("Delete From userTable (userName,age,birthPLace)");
GridView1.DataBind();
}
Make sure to create a static DataTable object and then use the following code:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
dt.Rows.RemoveAt(e.RowIndex);
GridView1.DataSource = dt;
GridView1.DataBind();
}
Try This Make sure You mention Datakeyname which is nothing but the column name (id) in your designer file
//your aspx code
<asp:GridView ID="dgUsers" runat="server" AutoGenerateSelectButton="True" OnDataBound="dgUsers_DataBound" OnRowDataBound="dgUsers_RowDataBound" OnSelectedIndexChanged="dgUsers_SelectedIndexChanged" AutoGenerateDeleteButton="True" OnRowDeleting="dgUsers_RowDeleting" DataKeyNames="id" OnRowCommand="dgUsers_RowCommand"></asp:GridView>
//Your aspx.cs Code
protected void dgUsers_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = Convert.ToInt32(dgUsers.DataKeys[e.RowIndex].Value);
string query = "delete from users where id= '" + id + "'";
//your remaining delete code
}
Your delete code looks like this
Gridview1.DeleteRow(e.RowIndex);
Gridview1.DataBind();
When you call Gridview1.DataBind() you will populate your gridview with the current datasource. So, it will delete all the existent rows, and it will add all the rows from CustomersSqlDataSource.
What you need to do is delete the row from the table that CustomersSqlDataSource querying.
You can do this very easy by setting a delete command to CustomersSqlDataSource, add a delete parameter, and then execute the delete command.
CustomersSqlDataSource.DeleteCommand = "DELETE FROM Customer Where CustomerID=#CustomerID"; // Customer is the name of the table where you take your data from. Maybe you named it different
CustomersSqlDataSource.DeleteParameters.Add("CustomerID", Gridview1.DataKeys[e.RowIndex].Values["CustomerID"].ToString());
CustomersSqlDataSource.Delete();
Gridview1.DataBind();
But take into account that this will delete the data from the database.
The easiest way is to create your GridView with some data source in ASP and call that data source in Row_Deletinng Event. For example if you have SqlDataSource1 as your GridView data source, your Row_Deleting event would be:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int ID = int.Parse(GridView1.Rows[e.RowIndex].FindControl("ID").toString());
string delete_command = "DELETE FROM your_table WHERE ID = " + ID;
SqlDataSource1.DeleteCommand = delete_command;
}
See the following code and make some changes to get the answer for your question
<%# Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
void CustomersGridView_RowDeleting
(Object sender, GridViewDeleteEventArgs e)
{
TableCell cell = CustomersGridView.Rows[e.RowIndex].Cells[2];
if (cell.Text == "Beaver")
{
e.Cancel = true;
Message.Text = "You cannot delete customer Beaver.";
}
else
{
Message.Text = "";
}
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>GridView RowDeleting Example</title>
</head>
<body>
<form id="form1" runat="server">
<h3>
GridView RowDeleting Example
</h3>
<asp:Label ID="Message" ForeColor="Red" runat="server" />
<br />
<asp:GridView ID="CustomersGridView" runat="server"
DataSourceID="CustomersSqlDataSource"
AutoGenerateColumns="False"
AutoGenerateDeleteButton="True"
OnRowDeleting="CustomersGridView_RowDeleting"
DataKeyNames="CustomerID,AddressID">
<Columns>
<asp:BoundField DataField="FirstName"
HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" />
<asp:BoundField DataField="City" HeaderText="City"
SortExpression="City" />
<asp:BoundField DataField="StateProvince" HeaderText="State"
SortExpression="StateProvince" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="CustomersSqlDataSource" runat="server"
SelectCommand="SELECT SalesLT.CustomerAddress.CustomerID,
SalesLT.CustomerAddress.AddressID,
SalesLT.Customer.FirstName,
SalesLT.Customer.LastName,
SalesLT.Address.City,
SalesLT.Address.StateProvince
FROM SalesLT.Customer
INNER JOIN SalesLT.CustomerAddress
ON SalesLT.Customer.CustomerID =
SalesLT.CustomerAddress.CustomerID
INNER JOIN SalesLT.Address ON SalesLT.CustomerAddress.AddressID =
SalesLT.Address.AddressID"
DeleteCommand="Delete from SalesLT.CustomerAddress where CustomerID =
#CustomerID and AddressID = #AddressID"
ConnectionString="<%$ ConnectionStrings:AdventureWorksLTConnectionString %>">
<DeleteParameters>
<asp:Parameter Name="AddressID" />
<asp:Parameter Name="CustomerID" />
</DeleteParameters>
</asp:SqlDataSource>
</form>
</body>
</html>
In Grid use this code having ID as your Primary Element so to uniquely identify each ROW
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="Hf_ID" runat="server" Value='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>
and to search the uique ID use the code in C# code behind (basically this is searching hidden field and storing it in a var)
protected void Grd_Registration_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
var ID = (HiddenField)Grd_Registration.Rows[e.RowIndex].FindControl("ID");
//Your Delete Logic Goes here having ID to delete
GridBind();
}
The solution is somewhat simple; once you have deleted the row from the datagrid (Your code ONLY removes the row from the grid and NOT the datasource) then you do not need to do anything else.
As you are doing a databind operation immediately after, without updating the datasource, you are re-adding all the rows from the source to the gridview control (including the row removed from the grid in the previous statement).
To simply delete from the grid without a datasource then just call the delete operation on the grid and that is all you need to do... no databinding is needed after that.
Add the below line in Page load,
ViewState["GetRecords"] = dt;
then try this,
protected void DeleteRows(object sender, GridViewDeleteEventArgs e)
{
dt = ViewState["GetRecords"] as DataTable;
dt.Rows.RemoveAt(e.RowIndex);
dt.AcceptChanges();
ViewState["GetRecords"] = dt;
BindData();
}
If you Still have any problem, send the code in BindData() method
I think you are doing same mistake of rebinding as mentioned in this link
How to delete row from gridview?
If I remember from your previous questions, you're binding to a DataTable. Try this:
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
DataTable sourceData = (DataTable)GridView1.DataSource;
sourceData.Rows[e.RowIndex].Delete();
GridVie1.DataSource = sourceData;
GridView1.DataBind();
}
Essentially, as I said in my comment, grab a copy of the GridView's DataSource, remove the row from it, then set the DataSource to the updated object and call DataBind() on it again.
Here is a trick with what you want to achieve. I was also having problem like you.
Its hard to get selected row and data key in RowDeleting Event But it is very easy to get selected row and datakeys in SelectedIndexChanged event. Here's an example-
protected void gv_SelectedIndexChanged(object sender, EventArgs e)
{
int index = gv.SelectedIndex;
int vehicleId = Convert.ToInt32(gv.DataKeys[index].Value);
SqlConnection con = new SqlConnection("-----");
SqlCommand com = new SqlCommand("DELETE FROM tbl WHERE vId = #vId", con);
com.Parameters.AddWithValue("#vId", vehicleId);
con.Open();
com.ExecuteNonQuery();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int index = GridView1.SelectedIndex;
int id = Convert.ToInt32(GridView1.DataKeys[index].Value);
SqlConnection con = new SqlConnection(str);
SqlCommand com = new SqlCommand("spDelete", con);
com.Parameters.AddWithValue("#PatientId", id);
con.Open();
com.ExecuteNonQuery();
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
I know this is a late answer but still it would help someone in need of a solution.
I recommend to use OnRowCommand for delete operation along with DataKeyNames, keep OnRowDeleting function to avoid exception.
<asp:gridview ID="Gridview1" runat="server" ShowFooter="true"
AutoGenerateColumns="false" OnRowDeleting="Gridview1_RowDeleting" OnRowCommand="Gridview1_RowCommand" DataKeyNames="ID">
Include DataKeyNames="ID" in the gridView and specify the same in link button.
<asp:LinkButton ID="lnkdelete" runat="server" CommandName="Delete" CommandArgument='<%#Eval("ID")%>'>Delete</asp:LinkButton>
protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
int ID = Convert.ToInt32(e.CommandArgument);
//now perform the delete operation using ID value
}
}
protected void Gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
//Leave it blank
}
If this is helpful, give me +
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
MySqlCommand cmd;
string id1 = GridView1.DataKeys[e.RowIndex].Value.ToString();
con.Open();
cmd = new MySqlCommand("delete from tableName where refno='" + id1 + "'", con);
cmd.ExecuteNonQuery();
con.Close();
BindView();
}
private void BindView()
{
GridView1.DataSource = ms.dTable("select * from table_name");
GridView1.DataBind();
}
//message box before deletion
protected void grdEmployee_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (DataControlFieldCell cell in e.Row.Cells)
{
foreach (Control control in cell.Controls)
{
LinkButton button = control as LinkButton;
if (button != null && button.CommandName == "Delete")
button.OnClientClick = "if (!confirm('Are you sure " +
"you want to delete this record?')) return false;";
}
}
}
}
//deletion
protected void grdEmployee_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
conn.Open();
int empid = Convert.ToInt32(((Label)grdEmployee.Rows[e.RowIndex].Cells[0].FindControl("lblIdBind")).Text);
SqlCommand cmdDelete = new SqlCommand("Delete from employee_details where id=" + empid, conn);
cmdDelete.ExecuteNonQuery();
conn.Close();
grdEmployee_refreshdata();
}
Related
I'm seeing this behavior on two of my pages, but I'm just going to ask about the one that's more important to me at the moment. I have a page that loads information from a database into a ASP gridview and then allows the user to add a detail to each populated line.
The issue I'm having is that when the 'Edit' button of the gridview and then subsequently the 'Update' or 'Cancel' button, it takes two click to actually fire the onclick event. A post back does take place on the first click, but nothing actually happens.
I'm including the code that seems relevant below. The page uses a master page and there are a number of divs involved with formatting, I'm excluding those.
Gridview and related controls:
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label Text="Plant Selector: " runat="server" />
<asp:DropDownList ID="ddlPlant" OnSelectedIndexChanged="ddlPlant_SelectedIndexChanged" runat="server" />
<asp:Button ID="btnUpdate" Text="Update" OnClick="btnUpdate_Click" runat="server" />
<p />
<asp:Label ID="lblTest" Text="" runat="server" />
<asp:Label ID="lblerror" Text="" ForeColor="Red" runat="server" />
<asp:GridView ID="gridview1" AutoGenerateColumns="false" runat="server" OnRowEditing="gridview1_RowEditing" OnRowCancelingEdit="gridview1_RowCancelingEdit" OnRowUpdating="gridview1_RowUpdating">
<Columns>
<asp:BoundField DataField="JobNum" HeaderText="Job Number" ReadOnly="true" />
<asp:BoundField DataField="ModelNum" HeaderText="Model" ReadOnly="true" />
<asp:BoundField DataField="Customer" HeaderText="Customer" ReadOnly="true" />
<asp:BoundField DataField="SchCompDate" HeaderText="Sch Comp Date" ReadOnly="true" />
<asp:TemplateField HeaderText="Details">
<EditItemTemplate>
<asp:TextBox ID="Txt" Width="98%" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label Text="Click Edit to add details of exception." runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:CommandField ShowEditButton="true" />
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gridview1" />
</Triggers>
</asp:UpdatePanel>
Sample image below:
Here is the code behind:
private string Plant { get; set; }
// This sets the default plant based off IP.
protected void Page_PreInit(Object sender, EventArgs e)
{
getPlantFromIP();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
populateDDL();
BindData();
}
else
{
Plant = ddlPlant.SelectedValue.ToString();
}
}
// Populates the drop down.
private void populateDDL()
{
ddlPlant.Items.Add("NC");
ddlPlant.Items.Add("WA");
setPlantInDDL();
}
private void setPlantInDDL()
{
if(Plant == "WA")
{
ddlPlant.SelectedIndex = 1;
}
if (Plant == "NC")
{
ddlPlant.SelectedIndex = 0;
}
}
private void getPlantFromIP()
{
if (Request.ServerVariables["REMOTE_ADDR"] == "70.103.118.100")
{
Plant = "WA";
//ddlPlant.SelectedIndex = 1;
}
else
{
Plant = "NC";
//ddlPlant.SelectedIndex = 0;
}
}
// Database Query.
private DataTable getDataFromDatabase()
{
DataTable rTable = new DataTable();
string plant = ddlPlant.SelectedValue.ToString();
using (var conn = new MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["workorderConnectionString"].ConnectionString))
{
conn.Open();
using (var cmd = conn.CreateCommand())
{
try
{
cmd.CommandText = #"SELECT * FROM reportdatatables.compliance_exception_report
WHERE ExceptionNoted = '0' AND Plant = #plant";
cmd.Parameters.AddWithValue("#plant", plant);
MySqlDataReader reader = cmd.ExecuteReader();
rTable.Load(reader);
reader.Close();
cmd.Dispose();
}
catch
{
}
finally
{
conn.Close();
}
}
}
return rTable;
}
// Binds the data from the database to the gridview.
private void BindData()
{
DataTable data = getDataFromDatabase().Copy();
gridview1.DataSource = data;
gridview1.DataBind();
}
protected void ddlPlant_SelectedIndexChanged(object sender, EventArgs e)
{
//Plant = ddlPlant.SelectedValue.ToString();
BindData();
}
// On edit call.
protected void gridview1_RowEditing(object sender, GridViewEditEventArgs e)
{
}
// On cancel call.
protected void gridview1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gridview1.EditIndex = -1;
}
protected void gridview1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
BindData();
}
Here's what I've tried:
-A lot of posts a read saw this behavior relating to autopostback settings of controls. As you can see I'm made sure to not have any control with the autopostback set to true.
-I had some concern that the behavior might be related to the updatepanel, but removing it doesn't change the behavior at all.
-I read that having AutoEventWireup="true" in your page tag can cause this. I DO have that in my page tag, but setting it to false does not fix the issue and prevents my dropdown from being populated on page load.
-There was another post that suggested the ID of the control could be changing between page load and post back. I monitored the IDs of those controls and I do not see any change in their ID.
So all that being said, I'm hoping someone has a clue as to what I'm missing. If there is any more information I can provide that might help, please let me know.
Thank you in advance.
Try this, which will make the grid editable
protected void gridview1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
for cancel also
protected void gridview1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
gridview1.EditIndex = -1;
BindData();
}
I have an aspx page that displays a gridview of questions waiting on review with 10 questions shown per page. If a question is selected it is opened in a new page where the reviewer can either submit a review or cancel and return to the list of questions needing review.
Currently this works fine, but have a request from the reviewers so that if they are on page 4 of the gridview when they go to a question, they get returned to page 4 if they hit cancel and return to the list of questions (currently they are returned to page 1).
So I am setting a couple session variables to capture the question selected and to capture the pageindex of the gridview control for future use. Trying to use the session variable for the questionId on the page load of the detail page, but it is not being passed. On returning to the Review List page the pageindex that is being set on the gridview is always 0, not the session variable.
Updated Gridview control (note two controls, one hyperlink(which should go away once the other linkbutton control works):
<asp:GridView ID="GridView1" runat="server" Caption="Questions Awaiting Review" AllowSorting="True" PagerSettings-Mode="NumericFirstLast" OnPageIndexChanging="GridView1_PageIndexChanging"
CaptionAlign="Top" EmptyDataText="No Questions Pending Review." PageSize="10" AllowPaging="true" PagerStyle-HorizontalAlign="Center" PagerStyle-Font-Size="Large" DataKeyNames="QuestionID"
AutoGenerateColumns="false" AlternatingRowStyle-BackColor="#cccccc">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="QuestionID" runat="server" Text='<%# Eval("QuestionID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="KeyObjective" HeaderText="Key Objective" ItemStyle-Width="250" />
<asp:BoundField DataField="SubmitDate" HeaderText="Submitted Date" ItemStyle-Width="60" />
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink ID="Details" runat="server" NavigateUrl='<%#"~/Review/ReviewDetail.aspx?Id=" + Eval("QuestionID") +"&PageIndex=" + GridView1.PageIndex %>'>View Question</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Details2" runat="server" Text="Session" OnClick="Session_OnClick"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
OnClick Event for the second button:
protected void Session_OnClick(object sender, EventArgs e)
{
Session["PageIndex"] = GridView1.PageIndex;
Session["QuestionId"] = GridView1.SelectedDataKey;
Response.Redirect("~/Review/ReviewDetail.aspx", false;
}
Connection string on the detail page which is now not getting a value for the parameter "QuestionID"; ):
SqlCommand command = new SqlCommand("QuestionDetail", Conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("#QuestionID", SqlDbType.BigInt));
command.Parameters["#QuestionID"].Value = Convert.ToInt64(Session["QuestionId"]);
Conn.Open();
SqlDataReader reader = command.ExecuteReader();
PageLoad and gridview binding on the ReviewList page that should be using session variable to set page of grid control, but is always going to default of page 0:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
bindGridView();
}
else
{
if (Convert.ToInt32(Session["PageIndex"]) !=0)
{
GridView1.PageIndex = Convert.ToInt32(Session["PageIndex"]);
bindGridView();
}
}
}
private void bindGridView()
{
string connectionString = WebConfigurationManager.ConnectionStrings["CS1"].ConnectionString;
string selectSQL = String.Format("Select QuestionID, KeyObjective, SubmitDate from Questions where Author <> '{0}' and QuestionID not in(Select QuestionID from Review where Reviewer = '{0}')", User.Identity.Name);
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(selectSQL, con);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
adapter.Fill(ds, "Review");
GridView1.DataSource = ds;
GridView1.DataBind();
}
Your error probably means that Request["Id"] is empty or does not exists. Always check if QueryStrings exist and do the conversions of user inputs that are likely to fail inside a try-catch block.
protected void Page_Load(object sender, EventArgs e)
{
long QuestionID = -1;
//check if the Id QueryString exists
if (Request.QueryString["Id"] != null)
{
//try to convert to int64
try
{
QuestionID = Convert.ToInt64(Request.QueryString["Id"]);
}
catch
{
}
}
//if valid QuestionID
if (QuestionID >= 0)
{
using (SqlConnection connection = new SqlConnection(Common.connectionString))
using (SqlCommand command = new SqlCommand("QuestionDetail", connection))
{
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#QuestionID", SqlDbType.BigInt).Value = QuestionID;
//try to execute the stored procedure
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
//handle sql error
Literal1.Text = ex.Message;
}
}
}
}
And why do you do a PostBack on the first button? That is not needed just to redirect to a different url. Change it to:
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#"~/Review/ReviewDetail.aspx?Id=" + Eval("QuestionID") %>'>View Question</asp:HyperLink>
Or with the Page Index also in the QueryString:
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl='<%#"~/Review/ReviewDetail.aspx?Id=" + Eval("QuestionID") + "&Page=" + GridView2.PageIndex %>'>View Question</asp:HyperLink>
UPDATE
If you really want to do a PostBack to set the Sessions you can use the OnRowCommand:
<asp:LinkButton ID="LinkButton1" CommandArgument='<%# Eval("QuestionID") %>' runat="server" CommandName="viewQuestion">View Question</asp:LinkButton>
CS
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "viewQuestion")
{
Session["PageIndex"] = GridView1.PageIndex;
Session["QuestionId"] = e.CommandArgument.ToString();
Response.Redirect("~/Review/ReviewDetail.aspx?Id=" + Convert.ToString(Session["QuestionId"]));
}
}
I am receiving the error "Input string was not in a correct format" on the line:
int index = Convert.ToInt32(e.CommandArgument);
My goal is to get the ID (both letters and numbers) from my Gridview (Cell 1 of the selected row), for processing the records in the DB associated with that ID.
Most of the pages that I found said to use the above code to find the row number for gridview.
My aspx page:
<asp:gridview ID="gridview1" runat="server" DataKeyNames="ID" AutoGenerateColumns="false" OnRowCommand="gridview1_RowCommand">
<columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btn_select" runat="server" Text="Select" CommandName="Select" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="Record_ID" DataField="ID" />
<asp:BoundField HeaderText="Record_Date" DataField="Date" />
</Columns>
</asp:gridview>
My Code Behind:
SqlCommand cmd = new SqlCommand();
protected void Page_Load(object sender, EventArgs e)
{
//code stuff
final();
}
protected void final()
{
//code stuff for populating the gridview. Gridview populates as expected.
}
protected void gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
int index = Convert.ToInt32(e.CommandArgument);//where I receive the error.
string id = gridview1.Rows[index].Cells[1].Text;
using (SqlConnection connection string)
{
try
{
cmd = new SqlCommand("DBSP", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#id", SqlDbType.Char).Value = id;
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
final();
}
catch (Exception ex)
{
//code stuff
}
}
}
}
A couple of other things I have tried are from:
Accessing GridView Cells Value
How to get cell value in GridView (WITHOUT using cell index)
Get the cell value of a GridView row
Getting value from a Gridview cell
as well as others.
You should assign the ID value to the CommandArgument of the LinkButton:
<asp:LinkButton ... CommandName="Select" CommandArgument='<%# Eval("ID") %>' />
The following line would give you the ID value, without having to get the text of the cell:
string ID = e.CommandArgument.ToString();
Alternatively, you could use the DataKeys to retrieve the ID value:
protected void gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
GridViewRow row = (e.CommandSource as Control).NamingContainer as GridViewRow;
string ID = gridView1.DataKeys[row.RowIndex].Values["ID"].ToString();
...
}
}
Code Behind
public void lbDelete_Click(object sender, EventArgs e)
{
LinkButton lb = sender as LinkButton;
GridViewRow gvrow = lb.NamingContainer as GridViewRow;
gvsize.DeleteRow(gvrow.RowIndex);
}
GridView:
<asp:GridView ID="gvsize" runat="server" ShowFooter="True" CellPadding="1" CellSpacing="2" AutoGenerateColumns="false" GridLines="Horizontal">
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="lnkdelete" runat="server" ForeColor="Blue" OnClick="lbDelete_Click">Delete</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</asp:GridView >
There are 2 rows in my gridview which I need to delete the row using the function above.
It throws an error "gvsize" RowDeletingEvent was not handled properly.
Is that necessary to use OnRowDeleted/OnRowDeleting in gridview which I feel not necessary??
As stated in How to delete row from gridview?
You are deleting the row from the gridview but you are then going and
calling databind again which is just refreshing the gridview to the
same state that the original datasource is in.
Either remove it from the datasource and then databind, or databind
and remove it from the gridview without redatabinding.
You can use row databound event to accomplish this task.
<asp:LinkButton ID="lnkBtnDel" runat="server" CommandName="DeleteRow" OnClientClick="return confirm('Are you sure you want to Delete this Record?');"">Delete</asp:LinkButton>
and in the rowdatabound event you can have
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
//incase you need the row index
int rowIndex = ((GridViewRow)((LinkButton)e.CommandSource).NamingContainer).RowIndex;
//followed by your code
}
}
Try this to delete row
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
dt.Rows.RemoveAt(e.RowIndex);
GridView1.DataSource = dt;
GridView1.DataBind();
}
You can also delete row from another method using Template Column
ASPX
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="imgDelete" runat="server" CommandName="deletenotice" ImageUrl="~/images/delete1.gif" alt="Delete"
OnClientClick="return confirm('Are you sure want to delete the current record ?')">
</asp:ImageButton>
</ItemTemplate>
</asp:TemplateField>
C# Code
protected void gvNoticeBoardDetails_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.ToLower().Equals("deletenotice"))
{
GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
NoticeBoard notice = new NoticeBoard();
HiddenField lblCust = (HiddenField)row.FindControl("hdngvMessageId");//Fetch the CourierId from the selected record
auditTrail.Action = DBAction.Delete;
Service simplyHRClient = new Service();
MessageClass messageClass = simplyHRClient.SaveNoticeBoard(notice, auditTrail);
if (messageClass.IsSuccess)
{
this.Page.AddValidationSummaryItem(messageClass.MessageText, "save");
showSummary.Style["display"] = string.Empty;
showSummary.Attributes["class"] = "success-message";
if (messageClass.RecordId != -1)
lblCust.Value = messageClass.RecordId.ToString();
}
else
{
this.Page.AddValidationSummaryItem(messageClass.MessageText, "save");
showSummary.Style["display"] = string.Empty;
showSummary.Attributes["class"] = "fail-message";
}
//Bind Again grid
GetAllNoticeBoard();
}
}
Hope it helps you
I have a gridview with some data and I want to add a checkbox column which can choose multiple rows. By clicking on it I want to save an primary key of row and change css class of row.
Using this article(step 2) I created itemtemplate,added there a checkbox(specifying ID as TransactionSelector), and add a checkedChange() to it. There I only change a css class of row and add a row index to arraylist. But when I click button with event which show this list, it has no items.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="TransactionSelector" runat="server"
oncheckedchanged="TransactionSelector_CheckedChanged" AutoPostBack="True" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="iTransactionsId" HeaderText="iTransactionsId"
SortExpression="iTransactionsId" />
<asp:BoundField DataField="mAmount" HeaderText="mAmount"
SortExpression="mAmount" />
<asp:BoundField DataField="vchTransactionType" HeaderText="vchTransactionType"
SortExpression="vchTransactionType" />
<asp:BoundField DataField="dtDate" HeaderText="dtDate"
SortExpression="dtDate" />
<asp:BoundField DataField="cStatus" HeaderText="cStatus"
SortExpression="cStatus" />
<asp:BoundField DataField="test123" HeaderText="test123"
SortExpression="test123" />
</Columns>
<RowStyle CssClass="unselectedRow" />
</asp:GridView>
</asp:Panel>
<asp:Panel ID="InfoPanel" runat="server" CssClass="infoPanel">
<asp:Button ID="ShowSelected" runat="server" Text="Button"
onclick="ShowSelected_Click" />
<asp:Label ID="InfoLabel" runat="server"></asp:Label>
</asp:Panel>
C Sharp code:
public partial class WebForm1 : System.Web.UI.Page
{
ArrayList indices = new ArrayList();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSourceID = "SqlDataSource1";
GridView1.DataBind();
}
}
protected void TransactionSelector_CheckedChanged(object sender, EventArgs e)
{
CheckBox cb = (CheckBox)sender;
GridViewRow row = (GridViewRow)cb.NamingContainer;
// row.CssClass = (cb.Checked) ? "selectedRow" : "unselectedRow";
if (cb.Checked)
{
row.CssClass = "selectedRow";
indices.Add(row.RowIndex);
}
else
{
row.CssClass = "unselectedRow";
indices.Remove(row.RowIndex);
}
}
protected void ShowSelected_Click(object sender, EventArgs e)
{
InfoLabel.Text = "";
foreach (int i in indices)
{
InfoLabel.Text += i.ToString() + "<br>";
}
}
}
}
You have to persist variable in postback using ViewState. Also its better if you use List<T> generic implementation rather than ArrayList
ViewState["Indices"] = indices;
And to recover it back
indices = ViewState["Indices"] as ArrayList;
As Habib said, you could use ViewState. You could also use ControlState instead, as shown here. If your code is in a custom control or user control, you may also need to override OnInit to
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
Page.RegisterRequiresControlState(this);
}
Please feel free to respond with feedback. I'm new at posting answers.