GridCheckBoxColumn with an string value - c#

I need that an GridCheckBoxColumn contains a string value from my table SQL for this row (id).
OBS: I work with ASP.NET framework 4, Telerik, C# and SQL Server.
The scenario:
in table SQL, i have multiple rows (columns sub_folder_path(varchar),groupM(varchar),groupR(varchar) are most important!).
in my webapp (asp.net), a call this table and create an RadGrid(Telerik) with informations from SQL (the same column name).
I need create an column in webapp (asp.net) 2 GridCheckBox (GroupR and GroupM), and for each row, I can choose just GroupR or GroupM.
When I select an option for GridCheckBox (GroupR and GroupM), I need move to .CS Group name selected (varchar) for each row.
My code asp.net
<telerik:GridCheckBoxColumn DataField="securityGroupR" HeaderText="Access to Modify"
SortExpression="securityGroupR" UniqueName="securityGroupR" DataType="System.String">
</telerik:GridCheckBoxColumn>
<telerik:GridCheckBoxColumn DataField="securityGroupM" HeaderText="Access to Modify"
SortExpression="securityGroupM" UniqueName="securityGroupM" DataType="System.String">
</telerik:GridCheckBoxColumn>
Error: String was not recognized as a valid Boolean.
How can I create GridCheckBox that passes for my .CS group name for each selected row?
Tks!

Please try with below code snippet.
.ASPX
<telerik:RadGrid ID="RadGrid1" runat="server" AutoGenerateColumns="false" OnNeedDataSource="RadGrid1_NeedDataSource"
OnItemDataBound="RadGrid1_ItemDataBound">
<MasterTableView>
<Columns>
<telerik:GridBoundColumn DataField="ID" UniqueName="ID" HeaderText="ID">
</telerik:GridBoundColumn>
<telerik:GridTemplateColumn>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" />
</ItemTemplate>
</telerik:GridTemplateColumn>
</Columns>
</MasterTableView>
</telerik:RadGrid>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Get selected Checbox" />
.ASPX.CS
protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
{
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("flag", typeof(string));
dt.Rows.Add(1, "true");
dt.Rows.Add(2, "true");
dt.Rows.Add(3, "false");
RadGrid1.DataSource = dt;
}
protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
{
if (e.Item is GridDataItem)
{
GridDataItem item = e.Item as GridDataItem;
DataRowView dr = item.DataItem as DataRowView; // Convert DataItem into Your Assigned Object
(item.FindControl("CheckBox1") as CheckBox).Checked = GetBoolValueFromString(Convert.ToString(dr["flag"]));
}
}
protected bool GetBoolValueFromString(string strFlag)
{
bool flag = false;
bool.TryParse(strFlag, out flag);
return flag;
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridDataItem item in RadGrid1.MasterTableView.Items)
{
if ((item.FindControl("CheckBox1") as CheckBox).Checked)
{
string strID = item["ID"].Text; // Get selected Checkbox's ID Field Value
}
}
}

Related

Why am I receiving "Input string not in correct format" while retreiving Gridview row index

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

Unable to persist data in GridView

have a GridView but cannot retrieve any of the data on post-back. I have set a break point at the start of Page_Init and Page_Load, on any post-back that is triggered the GridView.Rows.Count property is always 0. The GridView is defined as shown below:
<asp:GridView ID="TestGrid" runat="server" AllowSorting="False" DataKeyNames="ID,stock,percentage"
OnRowDataBound="GridViewTest_RowDataBound" EnableViewState="True"
OnRowUpdating="GridViewTest_OnRowUpdating" OnRowEditing="GridViewTest_OnRowEditing" OnRowCancelingEdit="GridViewTest_OnRowCancelingEdit"
AutoGenerateColumns="False">
<Columns>
<asp:CommandField ShowEditButton="True" CausesValidation="False"/>
<asp:BoundField DataField="Client" HeaderText="Client" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="Stock" HeaderText="Stock" InsertVisible="False" ReadOnly="True" />
<asp:BoundField DataField="DutyStatus" HeaderText="DutyStatus" InsertVisible="False" ReadOnly="True" />
<asp:TemplateField HeaderText="Percentage" InsertVisible="False">
<ItemTemplate>
<asp:Label ID="enhLbl" runat="server"><%#Eval("Percentage")%></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TbPercentage" runat="server" Text="<%#Bind("Percentage")%>" class="edit-field"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I have a check for IsPostBack in Page_Load and only bind the GridView to its DataSource if it's not a post-back.
The only other time it gets re-bound is in the GridViewTest_OnRowEditing, GridViewTest_OnRowUpdating and GridViewTest_OnRowCancelingEdit event handlers.
I am binding the GridView to a DataTable in the following way:
AGridView.DataSource = DataTableSplitParcels;
AGridView.DataBind();
AGridView.EnableViewState = true;
I don't know if it makes any difference, but the DataTable is created in code and the rows added within a loop.
Within Page_Load on a post-back I can see the GridView has its DataKeysArrayList property populated with the current values, however with it having no rows I am unable to retrieve any updated values.
The problem seems in the Page_Load event, which is refreshing your GridView with every call (irrespective of postback), and because of that you are losing what was entered by the user during update.
So put a debugger on your Page_Load and BindData events and see if it is getting called by Page_Load at all, and you need to stop that.. I tried a sample app and it worked at my end.. see below the code that I tried.
ASPX
<asp:GridView ID="TaskGridView" runat="server"
AutoGenerateEditButton="True"
AllowPaging="true"
OnRowEditing="TaskGridView_RowEditing"
OnRowCancelingEdit="TaskGridView_RowCancelingEdit"
OnRowUpdating="TaskGridView_RowUpdating"
OnPageIndexChanging="TaskGridView_PageIndexChanging">
</asp:GridView>
CS
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Create a new table.
DataTable taskTable = new DataTable("TaskList");
// Create the columns.
taskTable.Columns.Add("Id", typeof(int));
taskTable.Columns.Add("Description", typeof(string));
taskTable.Columns.Add("IsComplete", typeof(bool));
//Add data to the new table.
for (int i = 0; i < 20; i++)
{
DataRow tableRow = taskTable.NewRow();
tableRow["Id"] = i;
tableRow["Description"] = "Task " + i.ToString();
tableRow["IsComplete"] = false;
taskTable.Rows.Add(tableRow);
}
//Persist the table in the Session object.
Session["TaskTable"] = taskTable;
//Bind data to the GridView control.
BindData();
}
}
protected void TaskGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//Retrieve the table from the session object.
DataTable dt = (DataTable)Session["TaskTable"];
//Update the values.
GridViewRow row = TaskGridView.Rows[e.RowIndex];
dt.Rows[row.DataItemIndex]["Id"] = ((TextBox)(row.Cells[1].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["Description"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["IsComplete"] = ((CheckBox)(row.Cells[3].Controls[0])).Checked;
//Reset the edit index.
TaskGridView.EditIndex = -1;
//Bind data to the GridView control.
BindData();
}
private void BindData()
{
TaskGridView.DataSource = Session["TaskTable"];
TaskGridView.DataBind();
}
Source available here

How to delete a row without using OnRowDeleted/OnRowDeleting in gridview

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

Variables lost on postback in asp.net

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.

How to delete row in gridview using rowdeleting event?

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

Categories

Resources