GridView with CheckBox: How To Get Selected Rows in ASP.Net - c#

How to get gridview row values when checkbox is checked. I am using this code in button's click event, but it's not working .
Html Code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="100%"
DataKeyNames="ReportId" OnRowDataBound="GridView2_OnRowDataBound" ForeColor="#333333"
PageSize="5" Style="text-align: center">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxG1" runat="server" />
</ItemTemplate>
C# Code:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox CheckRow = (row.Cells[0].FindControl("CheckBoxG1") as CheckBox);
if (CheckRow.Checked)
{
}
}
}
}

I can not see how you bound data and where is your button placement. So this is work sample.
<asp:Button Text="text" runat="server" OnClick="Unnamed_Click" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ReportId" Width="100%"
ForeColor="#333333" PageSize="5" Style="text-align: center">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxG1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = new RowModel[]
{
new RowModel { ReportId = "1" },
new RowModel { ReportId = "2" },
new RowModel { ReportId = "3" }
};
GridView1.DataBind();
}
}
protected void Unnamed_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox CheckRow = (row.Cells[0].FindControl("CheckBoxG1") as CheckBox);
if (CheckRow.Checked)
{
}
}
}
}
public class RowModel
{
public string ReportId { get; set; }
}

In My sample code I have consider manually data while binding gridview because as you don't specify how you have bind your gridview through database or not, but it should work in both approaches.
My HTML code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Checkbox Selected Row Values from Gridview in Asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" DataKeyNames="UserId" AutoGenerateColumns="false" CellPadding="5" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
<asp:Button ID="btnProcess" Text="Get Selected Records" runat="server" Font-Bold="true" onclick="btnProcess_Click" />
<br />
<asp:Label ID="lblmsg" runat="server" />
</div>
</form>
</body>
</html>
Code Behind: This is just for binding GridView with proper data
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridviewData();
}
}
protected void BindGridviewData()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("Education", typeof(string));
dt.Columns.Add("Location", typeof(string));
DataRow dtrow = dt.NewRow(); //Create New Row
dtrow["UserId"] = 1; //Bind Data to Columns
dtrow["UserName"] = "SureshDasari";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Chennai";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); //Create New Row
dtrow["UserId"] = 2; //Bind Data to Columns
dtrow["UserName"] = "MadhavSai";
dtrow["Education"] = "MBA";
dtrow["Location"] = "Nagpur";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); //Create New Row
dtrow["UserId"] = 3; //Bind Data to Columns
dtrow["UserName"] = "MaheshDasari";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Nuzividu";
dt.Rows.Add(dtrow);
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
Code of Button_Click event
protected void btnProcess_Click(object sender, EventArgs e)
{
string str = string.Empty;
string strname = string.Empty;
string edu = string.Empty;
string location = string.Empty;
foreach (GridViewRow gvrow in gvDetails.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("chkSelect");
if (chk != null & chk.Checked)
{
//To Fetch the row index
//str += gvDetails.SelectedIndex.ToString();
//To Fetch the value of Selected Row.
str += gvDetails.DataKeys[gvrow.RowIndex].Value.ToString() + ',';
strname += gvrow.Cells[2].Text + ',';
edu += gvrow.Cells[3].Text + ',';
location += gvrow.Cells[4].Text + ',';
}
}
str = str.Trim(",".ToCharArray());
strname = strname.Trim(",".ToCharArray());
lblmsg.Text = "Selected UserIds: <b>" + str + "</b><br/>" + "Selected UserNames: <b>" + strname + "</b><br>" + " Education: <b>" + edu + "</b><br>" + " Location: <b>" + location + "</b><br>";
}

protected void Button1_Click(object sender, EventArgs e)
{
int count= 0;
foreach (GridViewRow gvindex in GridView1.Rows)
{
CheckBox chck = gvrow.FindControl("CheckBoxG1") as CheckBox;
if (chck.Checked)
{
GridView1.EditIndex = count;
DataBind(); //Your Databind Function
}
count++;
}

Related

Binding GridView Columns to CheckBoxList Dynamically in C#

I want to bind only Table Columns to CheckBoxList and then the selected columns should be displayed in a GridView.
My code so far is:
public void BindCheckBoxList(DataSet ds)
{
int i = 0;
foreach (DataColumn dc in ds.Tables[0].Columns)
{
ListItem li = new ListItem(dc.ToString(), i.ToString());
CheckBoxList1.Items.Add(li); i++;
}
}
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="HobbyId">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" Checked='<%# Eval("IsSelected") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Hobby" HeaderText="Hobby" ItemStyle-Width="150px" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="Save" />
in aspx.cs code
private void BindGrid()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT [HobbyId], [Hobby], [IsSelected] FROM Hobbies"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
}
}
}
protected void mainGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow &&
(e.Row.RowState == DataControlRowState.Normal ||
e.Row.RowState == DataControlRowState.Alternate))
{
if (e.Row.Cells[1].FindControl("selectCheckbox") == null)
{
CheckBox selectCheckbox = new CheckBox();
//Give id to check box whatever you like to
selectCheckbox.ID = "newSelectCheckbox";
e.Row.Cells[1].Controls.Add(selectCheckbox);
}
}
}
i think you use this code.
Here a complete example to hide GridView Columns based on a CheckBoxList.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//fill the datatable from the database
DataTable dt = //fill the table here...
//bind the table to the grid
GridView1.DataSource = dt;
GridView1.DataBind();
//loop all the datatable columns to fill the checkboxlist
for (int i = 0; i < dt.Columns.Count; i++)
{
CheckBoxList1.Items.Insert(i, new ListItem(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName, true));
}
}
}
protected void CheckBoxList1_TextChanged(object sender, EventArgs e)
{
//loop all checkboxlist items
foreach (ListItem item in CheckBoxList1.Items)
{
if (item.Selected == true)
{
//loop all the gridview columns
for (int i = 0; i < GridView1.Columns.Count; i++)
{
//check if the names match and hide the column
if (GridView1.HeaderRow.Cells[i].Text == item.Value)
{
GridView1.Columns[i].Visible = false;
}
}
}
}
}
And on the .aspx page
<asp:CheckBoxList ID="CheckBoxList1" runat="server" OnTextChanged="CheckBoxList1_TextChanged" AutoPostBack="true"></asp:CheckBoxList>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="field01" HeaderText="Column A" />
<asp:BoundField DataField="field02" HeaderText="Column B" />
<asp:BoundField DataField="field03" HeaderText="Column C" />
<asp:BoundField DataField="field04" HeaderText="Column D" />
<asp:BoundField DataField="field05" HeaderText="Column E" />
</Columns>
</asp:GridView>
Note that AutoGenerateColumns is set to false. If they are auto-generated the columns are not part of the GridView Columns Collection.
And of course HeaderText="xxx" must match the column names from the database that are stored in the DataTable.

what is the command of select in grid view asp.net

I have a GridView called gridview1
What I want is that if the user select or click on specific row some action will happen.
For example I want to get the value from that row and store it in a new variable.
How can I do it? I'm confused about what I should do to get the value?
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
string stuId = ?
}
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
AutoGenerateColumns="false" OnSelectedIndexChanged = "OnSelectedIndexChanged">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField Text="Select" CommandName="Select" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<br />
<u>Selected Row Values: </u>
<br />
<br />
<asp:Label ID="lblValues" runat="server" Text=""></asp:Label>
aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
//Accessing BoundField Column
string name = GridView1.SelectedRow.Cells[0].Text;
//Accessing TemplateField Column controls
string country = (GridView1.SelectedRow.FindControl("lblCountry") as Label).Text;
lblValues.Text = "<b>Name:</b> " + name + " <b>Country:</b> " + country;
}
you simply copy and paste your issue is resolve.
you could use like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false"
OnRowCommand = "OnRowCommand">
<Columns>
<asp:ButtonField CommandName = "ButtonField" DataTextField = "StudID"
ButtonType = "Button"/>
</Columns>
</asp:GridView>
protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = GridView1.Rows[index];
}

LinkButton in GridView dynamically

I am binding a grid with DataTable, there are two columns which I am using, and the result in GridView1 is is,
HostelName | HostelCode
Alpha | 1
Bravo | 2
Charlie | 3
Now I want this HostelCode as a LinkButton for all the records which are in database, so that I can do further actions while clicking LinkButton.
Any help ??
I am using this code, but its not working,
for (int i = 0; i < dt.Rows.Count; i++)
{
LinkButton lb = new LinkButton();
lb = (LinkButton)GridView1.SelectedRow.FindControl("lbtnSelect");
lb.Text = dt.Rows[1].ToString();
}
lbtnSelect is the ID of my linkbutton.
You can use link button in template field of gridview and Eval function to bind value in linkbutton in aspx page.
<asp:GridView runat="server" ID="gvrecords" CssClass="Gridview" DataKeyNames="HostelCode"
AutoGenerateColumns="false" HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="White"
OnRowDataBound="gvrecords_RowDataBound">
<Columns>
<asp:BoundField DataField="HostelName" HeaderText="Hostel Name" />
<asp:TemplateField HeaderText="Hostel Code">
<ItemTemplate>
<asp:LinkButton ID="lnkbtn" runat="server" OnClick="lnkbtn_Click" Text='<%#Eval("HostelCode")'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
ASPX CODE
<asp:GridView runat="server" ID="gvrecords" CssClass="Gridview" DataKeyNames="HostelCode"
AutoGenerateColumns="false" HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="White"
OnRowDataBound="gvrecords_RowDataBound">
<Columns>
<asp:BoundField DataField="HostelName" HeaderText="Hostel Name" />
<asp:TemplateField HeaderText="Hostel Code">
<ItemTemplate>
<asp:LinkButton ID="lnkbtn" runat="server" OnClick="lnkbtn_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CS CODE
public partial class Tests : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindHostelDetails();
}
}
protected void BindHostelDetails()
{
gvrecords.DataSource = DBData();
gvrecords.DataBind();
}
protected void gvrecords_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string HostelCode = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "HostelCode"));
LinkButton lnkbtnresult = (LinkButton)e.Row.FindControl("lnkbtn");
lnkbtnresult.Text = HostelCode;
}
}
protected void lnkbtn_Click(object sender, EventArgs e)
{
LinkButton lnkbtn = sender as LinkButton;
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
int hostelcode = Convert.ToInt32(gvrecords.DataKeys[gvrow.RowIndex].Value.ToString());
string HostelName = gvrow.Cells[0].Text;
Response.Write("<script> alert('" + "Hostel Name :"+ HostelName +" Hostel Code :"+ hostelcode + "'); </script>");
}
List<DTest> DBData()
{
List<DTest> _Dt = new List<DTest>();
_Dt.Add(new DTest { HostelName = "Alpha", HostelCode = "1" });
_Dt.Add(new DTest { HostelName = "Bravo", HostelCode = "2" });
_Dt.Add(new DTest { HostelName = "Charlie", HostelCode = "3" });
return _Dt;
}
}
public class DTest
{
public string HostelName { get; set; }
public string HostelCode { get; set; }
}

Fully editable gridview on single button click

I have a gridview and 2 buttons outside it. On button click all rows of gridview should become editable. I am using ITemplate class achive this task, but unable to complete it.
below is my code to get editable gridview:
public class GridViewTemplate : ITemplate
{
private DataControlRowType templateType;
private string columnName;
private string columnNameBinding;
private string controlType;
public GridViewTemplate(DataControlRowType type, string colname, string colNameBinding, string ctlType)
{
templateType = type;
columnName = colname;
columnNameBinding = colNameBinding;
controlType = ctlType;
}
public void InstantiateIn(System.Web.UI.Control container)
{
switch (templateType)
{
case DataControlRowType.Header:
Literal lc = new Literal();
lc.Text = columnName;
container.Controls.Add(lc);
break;
case DataControlRowType.DataRow:
if (controlType == "Label")
{
Label lb = new Label();
lb.ID = "lblName";
lb.DataBinding += new EventHandler(this.OnDataBinding);
container.Controls.Add(lb);
}
else if (controlType == "TextBox")
{
TextBox tb = new TextBox();
tb.ID = "txtWeightage" + columnNameBinding;
tb.DataBinding += new EventHandler(this.OnDataBinding);
container.Controls.Add(tb);
}
default:
break;
}
}
public void OnDataBinding(object sender, EventArgs e)
{
object bound_value_obj = null;
Control ctrl = (Control)sender;
IDataItemContainer data_item_container = (IDataItemContainer)ctrl.NamingContainer;
bound_value_obj = DataBinder.Eval(data_item_container.DataItem, columnName);
switch (templateType)
{
case DataControlRowType.Header:
Label lb = (Label)sender;
lb.Text = bound_value_obj.ToString();
break;
case DataControlRowType.DataRow:
TextBox txtbox = (TextBox)sender;
txtbox.Text = bound_value_obj.ToString();
break;
}
}
}
It's one sample :
This post demonstrate how to make a GridView editable all the time using C# asp.net.
step1-: Create a table with name " items" with following columns("iterm_no","name","price")
where "iterm_no" is identity column.as describe below
create table items
(
iterm_no int identity(1,1),
name varchar(20),
price numeric(10,2)
)
step2- Now create a web page with name(EditableGridView). as describe below.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="EditableGridView.aspx.cs" Inherits="EditableGridView" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Editable GridView</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AutoGenerateColumns="False"
BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px"
CellPadding="3" DataKeyNames="INTERM_NO" >
<FooterStyle BackColor="White" ForeColor="#000066" />
<Columns>
<asp:BoundField DataField="INTERM_NO" HeaderText="ITEM_N0" InsertVisible="False" ReadOnly="True"
SortExpression="INTERM_NO" />
<asp:TemplateField HeaderText="NAME" SortExpression="NAME">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("NAME") %>'
OnTextChanged="TextBox_TextChanged" BorderStyle="None"></asp:TextBox>
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("INTERM_NO") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="PRICE" SortExpression="PRICE">
<ItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("PRICE") %>'
OnTextChanged="TextBox_TextChanged" BorderStyle="None"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
</asp:GridView>
</div>
<asp:Button ID="btnUpdate" runat="server" onclick="btnUpdate_Click"
Text="Update" />
<asp:Label ID="lblMessage" runat="server"></asp:Label>
</form>
</body>
</html>
step 3- Go to your code behind (EditableGridView.cs) as describe below.
using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
public partial class EditableGridView : System.Web.UI.Page
{
SqlConnection con;
bool[] rowChanged;
protected void Page_Load(object sender, EventArgs e)
{
string conString = ConfigurationSettings.AppSettings["mycon"];
con = new SqlConnection(conString);
int totalRows = GridView1.Rows.Count;
rowChanged = new bool[totalRows];
if (!Page.IsPostBack)
{
BindGrid();
}
}
public void BindGrid()
{
SqlDataAdapter adap = new SqlDataAdapter("select * from items", con);
DataTable dt = new DataTable();
adap.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void TextBox_TextChanged(object sender, EventArgs e)
{
TextBox thisTextBox = (TextBox)sender;
GridViewRow thisGridViewRow = (GridViewRow)thisTextBox.Parent.Parent;
int row = thisGridViewRow.RowIndex;
rowChanged[row] = true;
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
int totalRows = GridView1.Rows.Count;
for (int r = 0; r < totalRows; r++)
{
if (rowChanged[r])
{
GridViewRow thisGridViewRow = GridView1.Rows[r];
HiddenField hf1 = (HiddenField)thisGridViewRow.FindControl("HiddenField1");
string pk = hf1.Value;
TextBox tb1 = (TextBox)thisGridViewRow.FindControl("TextBox1");
string name = tb1.Text;
TextBox tb2 = (TextBox)thisGridViewRow.FindControl("TextBox2");
decimal price = Convert.ToDecimal(tb2.Text);
SqlCommand cmd = new SqlCommand("update items set name='" + name + "' , price='" + price + "' where INTERM_NO=' " + pk + "'", con);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
int temp = cmd.ExecuteNonQuery();
if (temp > 0)
{
lblMessage.Text = "Operation perform successfully";
con.Close();
}
}
}
GridView1.DataBind();
BindGrid();
}
}
}
Note: If you have any query or question about this post contact us:
or try this . this link was helpful for your requirement

GridView Delete Row

I'm trying to delete a row in a gridview (the data is not in the database yet), so it should be a simple delete row, if anybody can please point me in the right direction....
This is what I have done:
else if (e.CommandName == "DeletePart")
{
int index = Convert.ToInt32(e.CommandArgument); //#1 line
GridView1.DeleteRow(index); //#2 line
}
The error that I am receiving is : "Input string was not in a correct format." (this happens on #1 line)...
This is how the gridview looks like: (use a linkbutton to do the delete)
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
EmptyDataText="No parts has been added to the model, please add a part."
BorderColor="Black" BorderStyle="Solid" BorderWidth="2px"
CellPadding="3" onrowcommand="GridView1_RowCommand"
onrowediting="GridView1_RowEditing" onrowdeleting="GridView1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="EditButton" runat="server" CssClass="EditButton" CommandName="Edit" Text="Edit" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="DeleteButton" runat="server" CssClass="DeleteButton" CommandName="DeletePart" CommandArgument='<%# Container.DataItemIndex %>' Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#FFFFCC" BorderColor="Black" BorderStyle="Solid"
BorderWidth="2px" />
</asp:GridView>
Class of how the gridview populated and binded:
public int companyID = 0;
public int methodID = 0;
DataTable dt;
#region SQLConnections
string connectionString = ConfigurationManager.ConnectionStrings["SOSConnectionString"].ConnectionString;
SqlConnection conn;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dt = new DataTable();
MakeDataTable();
EmptyDataString();
}
else
{
dt = (DataTable)ViewState["DataTable"];
}
ViewState["DataTable"] = dt;
}
#region GridView
private void EmptyDataString()
{
TemplateBuilder tmpEmptyDataTemplate = new TemplateBuilder();
tmpEmptyDataTemplate.AppendLiteralString("No parts has been added to the model, please add a part.");
GridView1.EmptyDataTemplate = tmpEmptyDataTemplate;
GridView1.DataBind();
}
private void MakeDataTable()
{
dt.Columns.Add("Item");
dt.Columns.Add("Quantity");
dt.Columns.Add("Price P/Quantity");
}
private void AddToDataTable()
{
DataRow dr = dt.NewRow();
dr["Item"] = txtPart.Text;
dr["Quantity"] = numQuantity.Text;
dr["Price P/Quantity"] = txtPricePQ.Text;
dt.Rows.Add(dr);
}
private void BindGrid()
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void btnAddPart_Click(object sender, EventArgs e)
{
AddToDataTable();
BindGrid();
ClearNewParts();
}
#endregion
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
txtPart.Text = row.Cells[2].Text;
numQuantity.Text = row.Cells[3].Text;
txtPricePQ.Text = row.Cells[4].Text;
}
}
else if (e.CommandName == "DeletePart")
{
//int iCount = GridView1.Rows.Count;
//for (int i = 1; i <= iCount; i++)
//{
// GridView1.DeleteRow(i);
//}
// int rowIndex = Convert.ToInt32(GridView1.SelectedRow);
int index = Convert.ToInt32(e.CommandArgument);
GridView1.DeleteRow(index);
//int index = Convert.ToInt32(e.CommandArgument);
//GridView1.DeleteRow(rowIndex);
}
GridView1.DataBind();
}
Found the solution, only needed to do a databound.... Here is the working code:
else if (e.CommandName == "Delete")
{
int index = Convert.ToInt32(e.CommandArgument);
GridView1.DeleteRow(index);
((DataTable)ViewState["DataTable"]).Rows[index].Delete();
((DataTable)ViewState["DataTable"]).AcceptChanges();
GridView1.DataSource = (DataTable)ViewState["Data"];
GridView1.DataBind();
}
Seems like you didn't mention CommandArgument property in the GridView.
<asp:GridView runat="server" ID="gv"
CommandName="DeletePart"
CommandArgument='<%# Container.DataItemIndex %>'>
</asp:GridView>
Add the CommandArgument as shown above.
Try this..
In ASPX:
<asp:GridView runat="server" ID="Gridview1" CommandName="delete" CommandArgument='<%#Container.DataItem.Index %>'/>
Cs:
else if (e.CommandName == "DeletePart")
{
int index = Convert.ToInt32(e.CommandArgument);
GridView1.DeleteRow(index);
}
try int.TryParse , this will solve the input string fromat problem , but why is it occuring that you need to check the CommandArgument you are setting.
else if (e.CommandName == "DeletePart")
{
int index =-1;
if(int.TryParse(e.CommandArgument,out index)) //#1 line
GridView1.DeleteRow(index); //#2 line
}
Thy This:)
<asp:GridView ID="GridView1" runat="server" CssClass="gridview"
HorizontalAlign="Left" PagerSettings-Visible="true" AllowPaging="True"
PageSize ="5" Width="300px" >
<Columns>
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
then code behinde:
Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
DirectCast(ViewState("CurrentDataReference"), DataTable).Rows.RemoveAt(e.RowIndex)
GridView1.DataSource = DirectCast(ViewState("CurrentDataReference"), DataTable)
GridView1.DataBind()
End Sub

Categories