Delete and Update Row from GridView on Image Button - c#

I want to delete the records from the Gridview on the click of ImageButton. Please see the GridView Code for your reference:-
<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="false" OnDataBound="grdCSRPageData_DataBound" PageSize="5" AllowPaging="true" OnPageIndexChanging="grdCSRPageData_PageIndexChanging" OnRowCommand="grdCSRPageData_RowCommand">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<asp:TemplateField ItemStyle-Width="30">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" />
<asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" />
<asp:BoundField DataField="Active" HeaderText="Active" ItemStyle-Width="30" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
<ItemTemplate>
<asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/images/edit.png" Width="15" Height="15" />
<span onclick="return confirm('Are you sure want to delete?')">
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="DeleteRow" />
</span>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Tried with 'RowCommand' property of GridView and stucked how to delete the Row
See the code:-
protected void grdCSRPageData_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
//incase you need the row index
int rowIndex = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).RowIndex;
int Id = Convert.ToInt32(e.CommandArgument);
//followed by your code
}
}

try this
protected void grdCSRPageData_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "DeleteRow")
{
int rowIndex = ((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).RowIndex;
grdCSRPageData.Rows.RemoveAt(rowIndex);
//delete from database
using (SqlConnection connection = new SqlConnection(connectionString))
{
int Id = Convert.ToInt32(e.CommandArgument);
string sql = "DELETE FROM YourTable WHERE ID = #ID";
SqlCommand cmd = new SqlCommand(sql,connection);
cmd.Parameters.AddWithValue("#ID",Id);
cmd.ExecuteNonQuery();
}
}
}
refer here for documentation about GridView remove.
SqlCommand documentation
update
to get the gridView from its row you can call this function
public static GridView GetParentGridView(GridViewRow row)
{
GridView gridView = (GridView)row.NamingContainer;
return gridView;
}
use it to get the gridview in my code
replace
grdCSRPageData.Rows.RemoveAt(rowIndex)
with
GetParentGridView((GridViewRow)((ImageButton)e.CommandSource).NamingContainer).Rows.RemoveAt(rowIndex)
be sure also to bind the grid only if there is no postback on page load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//bind the gridView
}
}

Tried with Something like this and it worked.:-
<asp:GridView ID="grdCSRPageData" runat="server" Width="100%" border="1" Style="border: 1px solid #E5E5E5;" CellPadding="3" AutoGenerateColumns="False" OnDataBound="grdCSRPageData_DataBound" AllowPaging="True" OnPageIndexChanging="grdCSRPageData_PageIndexChanging" DataKeyNames="Id" OnRowDeleting="grdCSRPageData_RowDeleting" OnClientClick="return confirm('Are you sure you want to delete this record?')">
<AlternatingRowStyle BackColor="#CCCCCC" />
<Columns>
<%-- <asp:TemplateField ItemStyle-Width="30">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>--%>
<asp:BoundField DataField="page_title" HeaderText="Page Title" ItemStyle-Width="30" />
<asp:BoundField DataField="page_description" HeaderText="Page Description" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_title" HeaderText="Meta Title" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_keywords" HeaderText="Meta Keywords" ItemStyle-Width="30" />
<asp:BoundField DataField="meta_description" HeaderText="Meta Description" ItemStyle-Width="30" />
<asp:BoundField DataField="Active" HeaderText="Active" ItemStyle-Width="30" />
<asp:TemplateField HeaderText="Action" HeaderStyle-Width="15%">
<ItemTemplate>
<%-- <asp:LinkButton ID="lbtnEdit" runat="server" CommandName="Edit" Text="Edit" />--%>
<asp:ImageButton ID="btnEdit" runat="server" ImageUrl="~/images/edit.png" Width="15" Height="15" />
<%-- <span onclick="return confirm('Are you sure want to delete?')"> -- %>
<%--<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandName="Delete" ></asp:LinkButton>--%>
<asp:ImageButton ID="btnDelete" AlternateText="Delete" ImageUrl="~/images/delete.png" runat="server" Width="15" Height="15" CommandName="Delete" CommandArgument='<%# Eval("Id") %>' CausesValidation="false" OnClientClick="return confirm('Are you sure you want to delete this record?')" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnUpdate" Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton ID="btnCancel" Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Also see the code behind:-
protected void grdCSRPageData_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
bool IsDeleted = false;
//getting key value, row id
int Id = Convert.ToInt32(grdCSRPageData.DataKeys[e.RowIndex].Value.ToString());
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "DELETE FROM tbl_Pages WHERE Id=#ID";
cmd.Parameters.AddWithValue("#ID", Id);
cmd.Connection = conn;
conn.Open();
IsDeleted = cmd.ExecuteNonQuery() > 0;
conn.Close();
}
}
if (IsDeleted)
{
//record has been deleted successfully!
//call here gridview bind method and replace it..
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Page Succesfully deleted');window.location ='csrpage.aspx';", true); ;
grdCSRPageData.DataBind();
}
else
{
//Error while deleting record
Response.Write("Some error");
}
}
Also the binding of the data should be inside the '(!IsPostBack)' method

Related

How to retrieve the value in GridView when I click on LinkButton of GridView

I am using gridview to display of data from database, in each row of the gridview I am having delete and edit link button. How can I get value of “NAME” and "DESCRIPTION" when I click on Delete or Edit Button in gridview.
The following is my code.
List.aspx
<div align="center" style="margin-top:50px">
<asp:GridView ID="gvDetails" runat="server" AutoGenerateColumns="false" CellPadding="5" runat="server">
<Columns>
<asp:BoundField HeaderText="Report Name" DataField="NAME" />
<asp:BoundField HeaderText="Report Description" DataField="DESCRIPTION" />
<asp:BoundField HeaderText="Report Group" DataField="REPORT_GROUP" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" OnClick="Btn_Delete_Click" />
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
</div>
List.aspx.cs
protected void Btn_Delete_Click(object sender, EventArgs e)
{
}
use command argument like this
<ItemTemplate>
<asp:LinkButton ID="btnDelete" Text="Delete" runat="server" CommandArguman='<%# Eval("Name")+","+Eval("DESCRIPTION") %>' OnClick="Btn_Delete_Click" />
<asp:LinkButton ID="btnEdit" Text="Edit" runat="server" CommandArguman='<%# Eval("Name")+","+Eval("DESCRIPTION") %>' OnClick="btnEdit_Click" />
</ItemTemplate>
in onclick
protected void Btn_Delete_Click(object sender, EventArgs e)
{
string strName=((LinkButton)sender).CommandArgument.Split(',')[0];
string strDescription=((LinkButton)sender).CommandArgument.Split(',')[1];
}
protected void btnEdit_Click_Click(object sender, EventArgs e)
{
string strName=((LinkButton)sender).CommandArgument.Split(',')[0];
string strDescription=((LinkButton)sender).CommandArgument.Split(',')[1];
}

Edit Gridview Row ASP.net

Struggling to edit a Gridview Row. Once I hit edit the gridview disappears, I guess because I only bind the grid on !IsPostBack - although the tutorial tells me to do it this way.
I have tried rebinding on postback which lets me edit the gridview but keeps the default values - not the new values.
Any help appreciated.
if (!IsPostBack)
{
if (Session["Order_ID"] != null)
{
showgrid(int.Parse(Session["Order_ID"].ToString()));
}
}
public void showgrid(int Order_ID)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["MyDbConn"].ToString());
string sqlstring = "Removed - is working";
SqlCommand cmd = new SqlCommand(sqlstring, conn);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
conn.Close();
if (ds.Tables[0].Rows.Count > 0)
{
gv_ExistingAds.DataSource = ds;
gv_ExistingAds.DataBind();
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
gv_ExistingAds.EditIndex = e.NewEditIndex;
showgrid(int.Parse(Session["Order_ID"].ToString()));
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
Label lb = (Label)gv_ExistingAds.Rows[e.RowIndex].FindControl("Label3");
TextBox tx1 = (TextBox)gv_ExistingAds.Rows[e.RowIndex].FindControl("TextBox3");
string tx11 = tx1.Text;
gv_ExistingAds.EditIndex = -1;
showgrid(int.Parse(Session["Order_ID"].ToString()));
}
HTML
<asp:GridView runat="server" AutoGenerateColumns="false" ShowFooter="True" ShowHeaderWhenEmpty="false" EmptyDataText="This order has no ads..."
ID="gv_ExistingAds" CssClass="table table-striped table-bordered table-hover"
Visible="true" DataKeyNames="Orders_Editions_ID, Cancelled, Order_ID" EnableViewState="true" OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:BoundField HeaderText="Publication Title" HtmlEncode="false" DataField="Publication_Title" />
<asp:BoundField HeaderText="Insertion Date" HtmlEncode="false" DataField="Insertion_Date" />
<asp:BoundField HeaderText="Advert Type" HtmlEncode="false" DataField="Description" />
<asp:BoundField DataField="Ad_Size" HeaderText="Size" ItemStyle-Width="150" />
<asp:BoundField DataField="Position" HeaderText="Position" ItemStyle-Width="150" />
<asp:BoundField DataField="Revenue" HeaderText="Revenue" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Note" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="Label3" runat="server" Text='<%# Eval("Note") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TextBox3" runat="server" Text='<%# Eval("Note") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Edit" ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="btnedit" runat="server" CommandName="Edit" Text="Edit"></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="btnupdate" runat="server" CommandName="Update" Text="Update"></asp:LinkButton>
<asp:LinkButton ID="btncancel" runat="server" CommandName="Cancel" Text="Cancel"></asp:LinkButton>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemStyle Width="165px" />
<ItemTemplate>
<%--<asp:LinkButton ID="btn_UpdateAdvert" ControlStyle-CssClass="btn btn-primary btn-xs" CommandName="Update_Advert" CommandArgument='<%#Eval("Orders_Editions_ID")%>' runat="server" Text="Update" CausesValidation="false" />--%>
<asp:LinkButton ID="btn_CancelAdvert" ControlStyle-CssClass="btn btn-warning btn-xs" CommandName="Cancel_Advert" CommandArgument='<%#Eval("Orders_Editions_ID")%>' runat="server" Text="Cancel" CausesValidation="false" />
<asp:LinkButton ID="btn_DeleteAdvert" ControlStyle-CssClass="btn btn-danger btn-xs" CommandName="Delete_Advert" CommandArgument='<%#Eval("Orders_Editions_ID")%>' runat="server" Text="Delete" CausesValidation="false" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#FF6699" />
</asp:GridView>

GridView - How to add a record with OnRowEditing and OnRowUpdating already enabled?

I've got a GridView which has OnRowEditing, UnRowUpdating and OnRowDeleting buttons. Now we want to let users add a new record. So currently I have this:
<asp:Panel runat="server" ID="ShowDiv1" Visible="false" BorderStyle="Solid" BorderWidth="0" Width="440px">
<asp:Label ID="lblShowDiv1Title" runat="server" Text="Executive Review Leads" Font-Bold="true"></asp:Label>
<br />
<div id="divGrid" style='width:450px; overflow:auto'>
<asp:GridView ID="DataGrid_Leads" runat="server"
AutoGenerateColumns="False"
ShowFooter="true"
CellPadding="1"
CssClass="hoverTable"
DataKeyNames="LOOKUP_VALUE"
OnRowCancelingEdit="DataGrid_Leads_CancelCommand"
OnRowEditing="DataGrid_Leads_EditCommand"
OnRowDeleting="DataGrid_Leads_DeleteCommand"
OnRowUpdating="DataGrid_Leads_UpdateCommand">
<Columns>
<asp:TemplateField HeaderText="Lead" ItemStyle-Width="230px">
<ItemTemplate>
<asp:Label ID="lbl_Name" runat="server" Width="220px" Text='<%#Eval("LOOKUP_DESCRIPTION") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_Name" runat="server" Width="220px" Text='<%#Eval("LOOKUP_DESCRIPTION") %>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="ntxt_Name" runat="server" Width="220px" ></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-Width="90px">
<ItemTemplate>
<asp:Button ID="btn_Edit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>
<asp:Button ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
<FooterTemplate>
<asp:Button ID="btn_Add" runat="server" Text="Add" CommandName="Add" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btn_Delete" runat="server" OnClientClick="javascript:return confirm('Are you sure?');" Text="Delete" CommandName="Delete" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID">
<ItemTemplate>
<asp:Label ID="lbl_ID" runat="server" Text='<%#Eval("LOOKUP_VALUE") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<AlternatingRowStyle Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<RowStyle BackColor="White" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<FooterStyle BackColor="#4DA6A6" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<HeaderStyle BackColor="#4DA6A6" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
<PagerSettings Mode="Numeric" Position="Bottom" />
<SelectedRowStyle BackColor="#e3f561" Font-Bold="False" Font-Italic="False"
Font-Overline="False" Font-Strikeout="False" Font-Underline="False" />
</asp:GridView>
<asp:Label ID="lblEmpty" runat="server" Visible="false" Style="font-weight:bold; font-size:large;"></asp:Label>
</div>
</asp:Panel>
Everything works fine in terms of displaying what I need to see. In the code-behind, I have a few functions to handle everything but adding a new record:
protected void DataGrid_Leads_EditCommand(object sender, GridViewEditEventArgs e)
{
DataGrid_Leads.EditIndex = e.NewEditIndex;
LoadLeadsGrid();
}
protected void DataGrid_Leads_UpdateCommand(object sender, GridViewUpdateEventArgs e)
{
int userid = Convert.ToInt32(DataGrid_Leads.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = (GridViewRow)DataGrid_Leads.Rows[e.RowIndex];
Label lbl_ID = (Label)DataGrid_Leads.Rows[e.RowIndex].FindControl("lbl_ID");
TextBox txt_Name = (TextBox)DataGrid_Leads.Rows[e.RowIndex].FindControl("txt_Name");
DataGrid_Leads.EditIndex = -1;
OracleConnection conn = GetConnection();
conn.Open();
////SqlCommand cmd = new SqlCommand("SELECT * FROM detail", conn);
OracleCommand cmd = new OracleCommand("UPDATE MY_VALUES set LOOKUP_DESCRIPTION = '" + txt_Name.Text + "' where LOOKUP_VALUE = '" + userid + "' AND LOOKUP_AREA = 'LEAD'", conn);
cmd.ExecuteNonQuery();
conn.Close();
LoadLeadsGrid();
}
protected void DataGrid_Leads_DeleteCommand(object sender, GridViewDeleteEventArgs e)
{
int userid = Convert.ToInt32(DataGrid_Leads.DataKeys[e.RowIndex].Value.ToString());
GridViewRow row = (GridViewRow)DataGrid_Leads.Rows[e.RowIndex];
Label lbldeleteid = (Label)row.FindControl("lbl_ID");
OracleConnection conn = GetConnection();
conn.Open();
OracleCommand cmd = new OracleCommand("DELETE FROM MY_VALUES where LOOKUP_VALUE = '" + userid + "' AND LOOKUP_AREA = 'LEAD'", conn);
cmd.ExecuteNonQuery();
conn.Close();
LoadLeadsGrid();
}
protected void DataGrid_Leads_CancelCommand(object sender, GridViewCancelEditEventArgs e)
{
DataGrid_Leads.EditIndex = -1;
LoadLeadsGrid();
}
So, how do I handle that "Add" button? I read online that you would use a RowCommand function, but when I added one and put a break point inside it, the code never entered that function.
Any help is appreciated.
try something like this
void ProductsGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple buttons are used in a GridView control, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Add")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Retrieve the row that contains the button clicked
// by the user from the Rows collection.
GridViewRow row = ProductsGridView.Rows[index];
// Create a new ListItem object for the product in the row.
ListItem item = new ListItem();
item.Text = Server.HtmlDecode(row.Cells[1].Text);
// If the product is not already in the ListBox, add the ListItem
// object to the Items collection of the ListBox control.
if (!ProductsListBox.Items.Contains(item))
{
ProductsListBox.Items.Add(item);
}
}
}
<asp:GridView ID="ProductsGridView"
DataSourceID="ProductsDataSource"
AllowPaging="true"
AutoGenerateColumns="false"
OnRowCommand="ProductsGridView_RowCommand"
OnRowCreated="ProductsGridView_RowCreated"
runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server"
ID="AddButton"
CommandName="Add"
Text="Add" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Name"
HeaderText="Product Name"/>
<asp:BoundField DataField="ProductNumber"
HeaderText="Product Number"/>
</Columns>
</asp:GridView>
you dont need gridview command. you can add command to directly add button..
<asp:Button ID="btn_Add" runat="server" Text="Add" CommandName="Add" />
change to
<asp:Button ID="btn_Add" runat="server" Text="Add" OnClick="btn_Add_Click" />
server side :
protected void btn_Add_Click(object sender, EventArgs e)
{
var textBox = GridView1.FooterRow.FindControl("ntxt_Name") as TextBox;
if (textBox != null)
{
var value = textBox.Text;
// insert operation
}
}

how to update a row through a row button click

i have a button in my gridview with the ID "btnApprove". what i want is when the user clicks the button, the row "Status" will be updated to 'Approved'. how can i acheive that? one row will only be updated when the button is clicked depending on the transaction number
here is my aspx code.
<asp:UpdatePanel ID="panel1" runat="server">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="TransactionID" OnRowDataBound="GridView1_OnRowDataBound" OnRowCommand="GridView1_RowCommand" CellPadding="4" AllowPaging="true" PageIndex="2" OnPageIndexChanging="GridView1_PageIndexChanging" HeaderStyle-BackColor ="CornflowerBlue" BorderWidth="1" BorderColor="Gray" Width="100%" CssClass=" table table-hover" >
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkHeader" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<img style="cursor:pointer" src ="../Images/Icons/plus2.png" />
<asp:Panel ID ="pnlDetails" runat="server" Style="display: none">
<asp:GridView ID="gvDet" runat="server" AutoGenerateColumns="false" CssClass="ChildGrid">
<Columns>
<%--<asp:BoundField ItemStyle-Width="20px" DataField="ID" HeaderText="ID" />--%>
<asp:BoundField ItemStyle-Width="200px" DataField="ItemType" HeaderText="Type" />
<asp:BoundField ItemStyle-Width="250px" DataField="ItemModel" HeaderText="Model" />
<asp:BoundField ItemStyle-Width="140px" DataField="ItemQuantity" HeaderText="Requested Quantity" />
<asp:BoundField ItemStyle-Width="80px" DataField="ItemUnit" HeaderText="Unit" />
<asp:BoundField ItemStyle-Width="100px" DataField="ItemDate" HeaderText="Date Needed" />
<asp:BoundField ItemStyle-Width="200px" DataField="ItemDesc" HeaderText="Description" />
<%--<asp:BoundField ItemStyle-Width="80px" DataField="ItemStatus" HeaderText="Status" />--%>
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ItemStyle-Width="150px" DataField="TransactionID" HeaderText="Transaction Number" />
<asp:BoundField ItemStyle-Width="150px" DataField="DateFiled" HeaderText ="Date Filed" />
<asp:BoundField ItemStyle-Width="150px" DataField="ReqName" HeaderText="Name" />
<asp:BoundField ItemStyle-Width="150px" DataField="ReqCompany" HeaderText="Company" />
<asp:BoundField ItemStyle-Width="150px" DataField="ReqBranch" HeaderText="Branch" />
<asp:BoundField ItemStyle-Width="150px" DataField="ReqBU" HeaderText="Business Unit" />
<asp:BoundField ItemStyle-Width="150px" DataField="ReqDept" HeaderText="Department" />
<asp:BoundField ItemStyle-Width="150px" DataField="ReqSection" HeaderText="Section" />
<asp:BoundField ItemStyle-Width="150px" DataField="TransStatus" HeaderText="Status" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnApprove" runat="server" Text="Approve" OnClick="btnApprove_Click" CssClass="btn btn-primary" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="CornflowerBlue" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GridView1" />
</Triggers>
</asp:UpdatePanel>
Update here is my data source of my GridView
public void showTable()
{
Utility u = new Utility();
string conn = u.connect();
SqlConnection connUser = new SqlConnection(conn);
SqlDataAdapter adp = new SqlDataAdapter("select * from MosefTransaction where TransStatus = 'Pending'", connUser);
DataTable dt = new DataTable();
connUser.Open();
adp.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
}
Add CommandArgument='<%# Container.DataItemIndex %>' to your button and in your code behind you can get the row that raised the event on Gridview's RowCommand event
<asp:Button ID="btnApprove" runat="server" Text="Approve" CommandName="ApproveTransaction" CommandArgument='<%# Container.DataItemIndex %>'/>
In your codebehind subscribe to gridview's row command event.
protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "ApproveTransaction")
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = gvInfo.Rows[index];
string cellText = row.Cells[2].Text;
//Update your data in database here and rebind the gridview to updated data
}
}

Imagebutton not giving an index off gridview so modal cant open

Hi i have a gridview with a button on each row that opens a modal and it works. For testing purposes i gave my imagebutton the same commandName to see if it would also open the modal. Unfortunately it did not...
After a little debugging i found that the imagebutton does not return a index (the row number) so my details modal can not display as i get error:
An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code
Additional information: Input string was not in a correct format.
I was wondering how i can pass the index number of the row using imagebutton.
I have included my code below:
markup
<asp:UpdatePanel ID="UserGridViewControl" runat="server">
<ContentTemplate>
<asp:GridView ID="GridViewUsers" runat="server" Width="940px" HorizontalAlign="Center"
OnRowCommand="GridView1_RowCommand" OnRowDataBound="GridView1_RowDataBound" AutoGenerateColumns="false" AllowPaging="true"
DataKeyNames="Ref" CssClass="table table-hover table-striped" OnPageIndexChanging="GridViewUsers_PageIndexChanging"
AllowSorting="true" OnSorting="GridViewUsers_Sorting">
<Columns>
<asp:BoundField DataField="Ref" SortExpression="Ref" HeaderText="Ref #" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="Listed" SortExpression="Listed" HeaderText="Listed" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="DateListed" dataformatstring="{0:MMMM d, yyyy}" SortExpression="DateListed" HeaderText="Date Listed" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="Type" SortExpression="Type" HeaderText="Type" HeaderStyle-HorizontalAlign="Left" />
<asp:ButtonField CommandName="editRecord" ControlStyle-CssClass="btn btn-info" ButtonType="Button" Text="View Services" HeaderText="Additional Services">
<ControlStyle CssClass="btn btn-info"></ControlStyle>
</asp:ButtonField>
<asp:BoundField DataField="London" SortExpression="London" HeaderText="London" HeaderStyle-HorizontalAlign="Left" />
<asp:BoundField DataField="MoveInDate" dataformatstring="{0:MMMM d, yyyy}" SortExpression="MoveInDate" HeaderText="Movie in Date" HeaderStyle-HorizontalAlign="Left" />
<asp:TemplateField HeaderText="Image">
<ItemTemplate>
<asp:ImageButton ID="ImageButton1" CommandName="detail" ButtonType="Button" runat="server" />
<asp:ImageButton ID="ImageButton2" runat="server" />
<asp:ImageButton ID="ImageButton3" runat="server" />
<asp:ImageButton ID="ImageButton4" runat="server" />
<asp:ImageButton ID="ImageButton5" runat="server" />
<asp:ImageButton ID="ImageButton6" runat="server" />
<asp:ImageButton ID="ImageButton7" runat="server" />
<asp:ImageButton ID="ImageButton8" runat="server" />
<asp:ImageButton ID="ImageButton9" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField CommandName="detail" ControlStyle-CssClass="btn btn-info" ButtonType="Button" Text="Detail" HeaderText="Details">
<ControlStyle CssClass="btn btn-info"></ControlStyle>
</asp:ButtonField>
</Columns>
</asp:GridView>
</ContentTemplate>
<Triggers>
</Triggers>
</asp:UpdatePanel>
Codebehind
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName.Equals("detail"))
{
LoadSortedDB();
int index = Convert.ToInt32(e.CommandArgument); // Breaks Here as there is no value in command argument
Int32 LoweredEmailCheck = Convert.ToInt32(GridViewUsers.DataKeys[index].Value);
IEnumerable<DataRow> query = from i in dt.AsEnumerable()
where i.Field<Int32>("Ref").Equals(LoweredEmailCheck)
select i;
DataTable detailTable = query.CopyToDataTable<DataRow>();
DetailsView1.DataSource = detailTable;
DetailsView1.DataBind();
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append(#"<script type='text/javascript'>");
sb.Append("$('#detailModal').modal('show');");
sb.Append(#"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "DetailModalScript", sb.ToString(), false);
}
}
use find to get object of asp ajax modal popup
with id:
var modalobj=$find("<%=modalid.ClientID%>");
modalobj.show();
with Behaviourid:
var modalobj=$find("Behaviourid");
modalobj.show();
Working with your code:
sb.Append(#"<script type='text/javascript'>");
sb.Append("$find('detailModal').show();");
sb.Append(#"</script>");
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "DetailModalScript", sb.ToString(), false);
Finding modal popup with Behaviourid

Categories