GridView Delete Confirm ButtonField - c#

I want to delete a row form my gridview with confirm by javascript.
My gridview looks like:
<asp:GridView ID="GridView1" runat="server" onrowcommand="GridView1_RowCommand">
<Columns>
<asp:ButtonField CommandName="delete" Text="Delete" />
</Columns>
</asp:GridView>
I already tried do with TempleField and it works, but the problem is getting the value of the select row to delete from database.
I tried like this:
<asp:GridView ID="GridView1" runat="server" onrowcommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnSave" runat="server" Text="Delete" OnClientClick="return confirm('Do you want to delete?')" CommandName="delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And tried get the value like this:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "delete")
{
int index = Convert.ToInt32(e.CommandArgument);
string id = GridView1.Rows[index].Cells[1].Text.ToString();
Response.Write(id);
}
}
But it throws a FormatException on
int index = Convert.ToInt32(e.CommandArgument);
Can somebody help me? Sorry but my English is bad.

You need to set the CommandArgument from the button tag
<asp:Button ID="btnSave" runat="server" Text="Delete" OnClientClick="return confirm('Do you want to delete?')" CommandName="delete" CommandArgument="<%# ((GridViewRow) Container).RowIndex %>"/>
Here is more info on how to use CommandArgument

Related

How to correctly get cell value in gridview after clicking on a linkbutton inside a gridview and enable correct async postback to display a modal

I am making a reservation system and currently stuck on the following situation.
Basically I have a GridView which is loaded with the reservation ID and two LinkButton which opens a modal popup to enable the customer to view the details.
What I want to achieve is that when I click any LinkButton, it will show the ID from the first cell of a GridViewRow.
I have tried these methods here, here, here, and here but it still doesn't work. Is there any way to do it, Aside from using a SELECT Command and does involve async postback or if async postback is not possible with this, any fix recommended?
Here is my GridView code:
<asp:UpdatePanel runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="gvReservationSummaries"/>
</Triggers>
<ContentTemplate>
<h2>Reservations</h2>
<br />
<asp:GridView ID="gvReservationSummaries" runat="server"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1"
AllowPaging="True" ShowHeader="False" CellPadding="5" CellSpacing="5"
onrowcommand="Gridview1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server"><%# Eval("Master_Reservation_ID")%></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" CommandName="ViewReservationDetails" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'>View Reservation Details</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" CommandName="ViewReceiptDetails" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'>View Receipt Details</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:DB_9E4ABD_GratchiOBRSConnectionString2 %>"
SelectCommand="SELECT [Master_Reservation_ID] FROM [Master_Reservation] WHERE User_Unique_ID = #uuid">
<SelectParameters>
<asp:SessionParameter Name="uuid" SessionField="uid" />
</SelectParameters>
</asp:SqlDataSource>
<br />
<asp:Button ID="btnShowModal" runat="server" Text="Show Modal 1 (Debug Purposes Only)" onclick="btnShowModal_Click" />
<!--Here, put the details of the reservaton, plus options to edit reservation.-->
</ContentTemplate>
</asp:UpdatePanel>
</div>
</div>
<asp:Panel ID="reservationSummaryModal" runat="server" Width="500px" Height="500px" style="display: none; background-color:Black; color:#CCC;">
<asp:Button ID="btnExitRs" runat="server" Text="Hide Modal (Debug Purposes Only)" onclick="btnExitAct_Click" />
<asp:Label ID="lblReservationSummary" runat="server" Text="Label"></asp:Label>
</asp:Panel>
<asp:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="HiddenField1" PopupControlID="reservationSummaryModal" BackgroundCssClass="modalBg" CancelControlID="btnExitRs">
</asp:ModalPopupExtender>
<asp:HiddenField ID="HiddenField1" runat="server" />
And here is my codebehind:
protected void Gridview1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ViewReservationDetails")
{
//GridViewRow gvr = gvReservationSummaries.Rows[Convert.ToInt32(e.CommandArgument)];
gvReservationSummaries.SelectedIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow gvr = gvReservationSummaries.Rows[gvReservationSummaries.SelectedIndex];
lblReservationSummary.Text = "The id is: " + gvr.Cells[0].Text.ToString();
ModalPopupExtender1.Show();
}
else if (e.CommandName == "ViewReceiptDetails")
{
gvReservationSummaries.SelectedIndex = Convert.ToInt32(e.CommandArgument);
GridViewRow gvr = gvReservationSummaries.Rows[gvReservationSummaries.SelectedIndex];
lblReservationSummary.Text = "The id is: " + gvr.Cells[0].Text.ToString();
ModalPopupExtender1.Show();
}
else
{
}
}

How to get the Id from Gridview of Chechbox.checked?

I have GridView and a button as follows. Then i am binding the gridview with data from my database. GridView has two hiddenfield for Id and ClassIndex.
when i selecting a checkbox and click button, i want to get the corresponding Id and FileName.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="check" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hdfId" runat ="server" Value='<%#Eval("Id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hdfClssIndex" runat ="server" Value='<%#Eval("ClassIndex") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="lblFileName" runat ="server" Text='<%#Eval("FileName") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
and Button Like
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Send Request" />
the code behind button is
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
var check = row.FindControl("check") as CheckBox;
if (check.Checked)
{
int Id = Convert.ToInt32(row.Cells[1].Text);
//some logic follws here
}
}
}
but i am getting an error like
Input string was not in a correct format.
What is the error and how to solve it?
Your looping correct.
But you forgot to notice one thing here, when you wanted to access CheckBox you did a FindControl on row. Which means you are trying to find some control in that row.
Then why are you accessing HiddenField control inside row with row.Cell[1].Text?
Try to find that also.
int Id = Convert.ToInt32(((HiddenField)row.FindControl("hdfId")).Value);

How to know in which row a button is clicked in asp.net gridView

This is a simple gridView I m using in aspx web page
<asp:GridView ID="Order" runat="server" AutoGenerateColumns="False" ShowFooter="True" GridLines="none"
ItemType="MyProject.Models.TempList" SelectMethod="GetList" >
<Columns>
<asp:BoundField DataField="ItemID" HeaderText="ID" SortExpression="ItemID" />
<asp:TemplateField HeaderText="ItemName">
<ItemTemplate>
<asp:Label runat="server" ID="ItemName" Width="40" Visible="true" text="<%#: Item.Item.ItemName %>"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Price(each)">
<ItemTemplate>
<%#: String.Format("{0:c}", Convert.ToDouble(Item.Item.UnitPrice))%>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<div style="float:left">
<asp:Button ID="DeleteBtn" runat="server" Text="Delete" OnClick="DeleteBtn_Click"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I have 2+ items in a list<> which is populating the gridView, how can I tell (in the codeBehind.cs) that which Row the "DeleteBtn" was clicked on?
I was using a for loop to iterate every item in gridView using Rows[i] and used a check box to know which item wants to be deleted using a Update button.
But I want to do it directly on a custom created deletebutton.
Thanks in advance, I know I'm missing something silly.
The best way to do that is using CommandName and CommandArgument in your button declaration like that
<asp:Button ID="AddButton" runat="server" CommandName="AddToCart"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" Text="Add to Cart" />
you can pass any value in the case we pass the rowIndex, you can get a propertie from your object like that CommandArgument="<%# Eval("id") %>" after that you will handle the onRowCommand method
protected void GridView1_RowCommand(object sender,GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCart")
{
// Retrieve the row index stored in the
// CommandArgument property.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button
// from the Rows collection.
GridViewRow row = GridView1.Rows[index];
// Add code here to add the item to the shopping cart.
}
}
hope it helps :)
Use the button's CommandArgument property; assign Container.DataItemIndex to it. Then use the OnRowCommand event of the gridview and grab the index.
Sample aspx:
<asp:Label runat="server" ID="lblMsg" />
<asp:GridView runat="server" id="gvSample" AutoGenerateColumns="false" OnRowCommand="PerformOperation">
<Columns>
<asp:BoundField DataField="RowValue"/>
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Delete" runat="server" CommandName="MyCustomCommand" CommandArgument="<%# Container.DataItemIndex %>" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
PopulateGrid();
}
}
private void PopulateGrid()
{
gvSample.DataSource = Enumerable.Range(0, 10).Select(i => new { RowValue = i });
gvSample.DataBind();
}
protected void PerformOperation(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MyCustomCommand")
{
var rowIndex = int.Parse(e.CommandArgument);
lblMsg.Text = string.Format("Button on row index: {0} was clicked!", rowIndex);
}
}
Let the button field be given a CommandName, say for example a unique string myCommandName in the Edit columns dialog box. Don't worry about the CommandArgument. Then, in the Grid view Row command event, you can check which button (i.e. column) is clicked by tracing the command name like if e.commandname = "mycommandname", at the same time the CommandArgument will also be available as String and all we have to do is to converttoint32, something like intSelectedRow = convert.ToInt32(e.CommandArgument) which will give us the selected row's index.

Enabling And Disabling Buttons In GridView

I have added a button column to a gridview. I am populating the gridview with a datable through code then binding the datable to the grid.
I need to now look at the first column of the data and check if the text of the column is "NA" if it is the button in that column has to be disabled.....
How can I accomplish this? I am populating the data from code and the button is preadded to the grid in the markup
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:ButtonField Text="Delete" />
</Columns>
</asp:GridView>
GridView1.DataSource = dt;
GridView1.DataBind();
The best thing to do is implement the OnDataBinding method for a Button in a TemplateColumn.
Eg:
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" ID="btnDelete" CommandName="Delete"
Text="Delete" OnDataBinding="btnDelete_DataBinding" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Then in your codebehind implement your logic:
protected void btnDelete_DataBinding(object sender, System.EventArgs e)
{
Button btn = (Button)(sender);
btn.Enabled = !Eval("TheFieldInYourDataSourceToCompare").ToString().Equals("NA");
}
The advantage to doing it in this manner over the other posted answers:
No code in your markup
Code is localized to the Button control and can be reused if other Buttons require the same functionality.
Comparing to the DataSource value and not what the visual output is (this could tie into business logic for both rendering and checking).
Hope that helps.
Try this in the DataBound event handler:
protected void GridView1_DataBound(object sender, EventArgs e)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
if (GridView1.Rows[i].Cells[1].Text == "NA")
{
// Disable the button
}
}
}
This is just a general idea. You'll have to modify the code for your application.
Don't forget to add OnDataBound="GridView1_DataBound" to the markup for the GridView.
Maybe something like this.
Did the button a little differently
<asp:GridView ID="GridView1" runat="server" OnRowCommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" ID="Btn_Delete" CommandName="Delete" Text="delete"
Enabled='<%# GridView1.Rows[0].Cells[1].Text != "NA" %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You'll want to you Eval("someColumn") most likely instead of GridView1.Rows[0].Cells[1].Text
Perhaps you can use OnRowDataBound="GridViewRowEventHandler" to set the value to enabled or disabled?
you can try from markup as,
<asp:TemplateField HeaderText="QA signature">
<EditItemTemplate>
<asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Column6") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Column6") %>' Visible='<%# Eval("Column6") != "" %>' ></asp:Label>
<asp:Button ID="Button2" runat="server" Text="Sign Off" CssClass="cmdButton" Visible='<%# Eval("Column6") == "" %>' />
</ItemTemplate>
</asp:TemplateField>

Select any particular data from the gridview and dislay it in the label

hai pupils
I am doing a project on online education. In my project i display the trainees/trainers in in a gridview. If i select any data from the gridview it has to be dispalyed in the label kept below. How can i do this?
Thanks in advance for those who answers.
Use asp:LinkButton to show data in each column. Set commandArgument as the data. set same comandname and handle rowcommand in gridview rowcommand event.
try the following:
in aspx page:
<asp:GridView ID="GridView1" OnRowCommand="GridView1_RowCommand" runat="server">
<Columns>
<asp:TemplateField HeaderText="CategoryID">
<ItemTemplate>
<asp:LinkButton ID="lnkID" runat="server" CommandName="sel" CommandArgument='<%# DataBinder.Eval(Container,"DataItem.CategoryID") %>'
Text='<%# DataBinder.Eval(Container,"DataItem.CategoryID") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CategoryName">
<ItemTemplate>
<asp:LinkButton ID="lnkName" runat="server" CommandName="sel" CommandArgument='<%# DataBinder.Eval(Container,"DataItem.CategoryName") %>'
Text='<%# DataBinder.Eval(Container,"DataItem.CategoryName") %>'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Label ID="lblCat" runat="server"></asp:Label>
in aspx.cs page:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "sel")
{
lblCat.Text = e.CommandArgument;
}
}

Categories