Asp.net using Entity frame work and in grid view when i press delete button it delete the row, and then show this "The object cannot be deleted because it was not found in the ObjectStateManager.""
Here is ascx code :
<%# Control Language="C#" AutoEventWireup="true"
CodeBehind="ctrl_ResearcherMyResearch.ascx.cs"
Inherits="ITI.GeoXera.ASP.User_Controls.ctrl_ResearcherMyResearch" %>
<asp:GridView ID="grd_Researcher" runat="server" AutoGenerateColumns="False"
DataKeyNames="Id,Title" DataSourceID="Researcher"
OnRowDeleting="grd_Researcher_RowDeleting"
OnRowEditing="grd_Researcher_RowEditing"
OnRowUpdating="grd_Researcher_RowUpdating" PageSize="3" Width="900px"
AllowPaging="True" CellPadding="4" ForeColor="#333333" GridLines="None"
HorizontalAlign="Center" >
<AlternatingRowStyle HorizontalAlign="Center" VerticalAlign="Middle"
BackColor="White" />
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ReadOnly="True"
SortExpression="Id" >
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="Title" HeaderText="Title"
SortExpression="Title" >
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="Author" HeaderText="Author"
SortExpression="Author" >
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="Description" HeaderText="Description"
SortExpression="Description" >
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="LatitudeFrom" HeaderText="Lat"
SortExpression="LatitudeFrom" >
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" />
</asp:BoundField>
<asp:BoundField DataField="LongitudeFrom" HeaderText="Long"
SortExpression="LongitudeFrom" />
<asp:BoundField DataField="FkUser" HeaderText="FkUser"
SortExpression="FkUser" Visible="False" ReadOnly="True" />
<asp:BoundField DataField="Link" HeaderText="Link" SortExpression="Link"
/>
<asp:CommandField ButtonType="Button" DeleteText="" InsertText=""
NewText="" SelectText="" ShowEditButton="True" />
<asp:CommandField ButtonType="Button" InsertText="" NewText=""
SelectText="" ShowDeleteButton="True" />
</Columns>
<EditRowStyle HorizontalAlign="Center" VerticalAlign="Middle" Height="30px"
BackColor="#2461BF" Width="20px" Wrap="True" />
<EmptyDataRowStyle HorizontalAlign="Center" VerticalAlign="Middle" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderStyle HorizontalAlign="Center" VerticalAlign="Middle" Height="30px"
BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerSettings PageButtonCount="5" />
<PagerStyle VerticalAlign="Middle" BackColor="#2461BF" ForeColor="White"
HorizontalAlign="Center" />
<RowStyle HorizontalAlign="Center" VerticalAlign="Middle"
BackColor="#EFF3FB" Font-Strikeout="False" Width="50px" />
<SelectedRowStyle HorizontalAlign="Center" VerticalAlign="Middle"
BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
<SortedAscendingCellStyle BackColor="#F5F7FB" />
<SortedAscendingHeaderStyle BackColor="#6D95E1" />
<SortedDescendingCellStyle BackColor="#E9EBEF" />
<SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>
<asp:ObjectDataSource ID="Researcher" runat="server"
DataObjectTypeName="ITI.GeoXera.Model.Models.Research" DeleteMethod="Delete"
InsertMethod="Add" SelectMethod="GetAllBind"
TypeName="ITI.GeoXera.Data.Repositories.ResearchRepository"
UpdateMethod="Update"></asp:ObjectDataSource>
<p>
</p>
<div class="box box-info">
<asp:Panel ID="Panel1" runat="server" GroupingText=" Research Information">
<div class="box-body">
<div class="form-group">
<asp:Label CssClass="col-sm-2 control-label" ID="lbl_Title"
runat="server" Text="Title"></asp:Label>
<div class="col-sm-10">
<asp:TextBox CssClass="form-control" ID="txt_Title"
runat="server" AutoCompleteType="Disabled"></asp:TextBox>
<asp:RequiredFieldValidator ID="vldreq_Title" runat="server"
ControlToValidate="txt_Title" ForeColor="#CC0000" ToolTip="Please Enter
Research Title">*</asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<asp:Label ID="lbl_Author" runat="server" CssClass="col-sm-2
control-label" Text="Author"></asp:Label>
<div class="col-sm-10">
<asp:TextBox ID="txt_Author" runat="server"
AutoCompleteType="Disabled" CssClass="form-control" ></asp:TextBox>
<asp:RequiredFieldValidator ID="vldreq_Author" runat="server"
ErrorMessage="*" ForeColor="#CC0000" ToolTip="Please Enter Author Name"
ControlToValidate="txt_Author"></asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<asp:Label ID="lbl_Description" runat="server" CssClass="col-sm-2
control-label" Text="Description"></asp:Label>
<div class="col-sm-10">
<asp:TextBox ID="txt_Description" runat="server"
AutoCompleteType="Disabled" CssClass="form-control" ></asp:TextBox>
<asp:RequiredFieldValidator ID="vldreq_Description"
runat="server" ErrorMessage="*" ForeColor="#CC0000" ToolTip="Please Enter
Description" ControlToValidate="txt_Description">
</asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<asp:Label CssClass="col-sm-2 control-label" ID="lbl_LatitudeFrom"
runat="server" Text="Latitude From"></asp:Label>
<div class="col-sm-4">
<asp:TextBox CssClass="form-control" ID="txt_LatitudeFrom"
runat="server" AutoCompleteType="Disabled"></asp:TextBox>
<asp:RequiredFieldValidator ID="vlrLatFrom" runat="server"
ControlToValidate="txt_LatitudeFrom" ForeColor="#FF3300" ToolTip="Please
Enter
Required Data">*</asp:RequiredFieldValidator>
</div>
<asp:Label CssClass="col-sm-2 control-label" ID="lbl_LatitudeTo"
runat="server" Text="Latitude To"></asp:Label>
<div class="col-sm-4">
<asp:TextBox CssClass="form-control" ID="txt_LatitudeTo"
runat="server" AutoCompleteType="Disabled"></asp:TextBox>
<asp:RequiredFieldValidator ID="vlrLatTo" runat="server"
ControlToValidate="txt_LatitudeTo" ForeColor="#FF3300" ToolTip="Please Enter
Required Data">*</asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<asp:Label CssClass="col-sm-2 control-label" ID="lbl_LongitudeFrom"
runat="server" Text="Longitude From"></asp:Label>
<div class="col-sm-4">
<asp:TextBox CssClass="form-control" ID="txt_LongitudeFrom"
runat="server" AutoCompleteType="Disabled"></asp:TextBox>
<asp:RequiredFieldValidator ID="vlrLongFrom" runat="server"
ControlToValidate="txt_LongitudeFrom" ForeColor="#FF3300" ToolTip="Please
Enter
Required Data">*</asp:RequiredFieldValidator>
</div>
<asp:Label CssClass="col-sm-2 control-label" ID="lbl_LongitudeTo"
runat="server" Text="Longitude To"></asp:Label>
<div class="col-sm-4">
<asp:TextBox CssClass="form-control" ID="txt_LongitudeTo"
runat="server" AutoCompleteType="Disabled"></asp:TextBox>
<asp:RequiredFieldValidator ID="vlrLongTo" runat="server"
ControlToValidate="txt_LongitudeTo" ForeColor="#FF3300" ToolTip="Please
Enter Required Data">*</asp:RequiredFieldValidator>
</div>
</div>
<div class="form-group">
<asp:Label CssClass="col-sm-2 control-label" ID="lbl_Link"
runat="server" Text="Link"></asp:Label>
<div class="col-sm-10">
<asp:TextBox CssClass="form-control" ID="txt_Link"
runat="server" AutoCompleteType="Disabled"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ControlToValidate="txt_Link" ForeColor="#FF3300"
ToolTip="Please Enter Link Path">*</asp:RequiredFieldValidator>
</div>
</div>
</div>
<div class="box-footer">
<asp:Button CssClass="btn btn-info pull-right" ID="btn_SaveInfo"
runat="server" Text="Save" OnClick="btn_SaveInfo_OnClick" />
</div>
ascx.cs code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Windows.Forms;
using ITI.GeoXera.Data.InfraStructure;
using ITI.GeoXera.Data.Repositories;
using ITI.GeoXera.Model.Models;
namespace ITI.GeoXera.ASP.User_Controls
{
public partial class ctrl_ResearcherMyResearch : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//grd_Researcher.DataBind();
}
}
protected void grd_Researcher_RowUpdating(object sender,
GridViewUpdateEventArgs e)
{
using (UnitOfWork uof = new UnitOfWork())
{
int index = e.RowIndex;
Research research = new Research();
User user = new User();
research.Id = Convert.ToInt32(grd_Researcher.DataKeys[index]
["Id"]);
research.Title = e.NewValues["Title"].ToString();
research.Description = e.NewValues["Description"].ToString();
research.Author = e.NewValues["Author"].ToString();
research.LatitudeFrom =
Convert.ToDouble(e.NewValues["LatitudeFrom"]);
research.LatitudeTo =
Convert.ToDouble(e.NewValues["LatitudeTo"]);
research.LongitudeFrom =
Convert.ToDouble(e.NewValues["LongitudeFrom"]);
research.LongitudeTo =
Convert.ToDouble(e.NewValues["LongitudeTo"]);
research.Link = e.NewValues["Link"].ToString();
research.FkUser = 1;
uof.ResearchRepository.Update(research);
grd_Researcher.EditIndex = -1;
grd_Researcher.DataBind();
uof.Commit();
}
}
protected void grd_Researcher_RowEditing(object sender,
GridViewEditEventArgs e)
{
using (UnitOfWork uof = new UnitOfWork())
{
grd_Researcher.EditIndex = e.NewEditIndex;
grd_Researcher.DataBind();
}
}
protected void grd_Researcher_RowDeleting(object sender,
GridViewDeleteEventArgs e)
{
string Title =
Convert.ToString(grd_Researcher.DataKeys[e.RowIndex].Values[1]);
using (UnitOfWork uof = new UnitOfWork())
{
if (Title != null || Title != "")
{
Research research =
uof.ResearchRepository.GetAll().Where(res => res.Title ==
Title).FirstOrDefault();
if (research != null)
{
uof.ResearchRepository.Delete(research);
uof.Commit();
//grd_Researcher.DataSource =
uof.ResearchRepository.GetAllBind();
MessageBox.Show("Deleted successfully.");
}
else
{
MessageBox.Show("Not Found");
}
}
grd_Researcher.EditIndex = -1;
grd_Researcher.DataBind();
}
}
protected void btn_SaveInfo_OnClick(object sender, EventArgs e)
{
using (UnitOfWork uof = new UnitOfWork())
{
User u = new User();
bool entryFound = false;
Research research = new Research();
foreach (GridViewRow row in grd_Researcher.Rows)
{
object val1 = row.Cells[1].Text;
if (val1 != null && val1.ToString() == txt_Title.Text)
{
MessageBox.Show("Entry already exist");
entryFound = true;
break;
}
}
if (!entryFound)
{
research.Title = txt_Title.Text;
research.Author = txt_Author.Text;
research.Description = txt_Description.Text;
research.LatitudeFrom =
Convert.ToDouble(txt_LatitudeFrom.Text);
research.LatitudeTo = Convert.ToDouble(txt_LatitudeTo.Text);
research.LongitudeFrom =
Convert.ToDouble(txt_LongitudeFrom.Text);
research.LongitudeTo =
Convert.ToDouble(txt_LongitudeTo.Text);
research.Link = txt_Link.Text;
research.FkUser = Convert.ToInt32(Session["UserID"]);
uof.ResearchRepository.Add(research);
grd_Researcher.DataBind();
uof.Commit();
MessageBox.Show("Data Added");
foreach (var control in this.Controls)
{
System.Web.UI.WebControls.TextBox tb = control as
System.Web.UI.WebControls.TextBox;
if (tb != null)
{
tb.Text = string.Empty;
}
}
uof.ResearchRepository.GetAllBind();
}
}
}
}
}
Thanks in advance
Are you sure the row you are trying to remove has a value in the "Title". The code you have post withif (Title != null || Title != "") has bug that would allow both null and empty values. It should be if (Title != null && Title != "") if you are trying to prevent that.
Related
I have a grid view which has two autogenerated Edit and delete buttons in first cell itself. The code is as below
<asp:GridView ID="grdStudent" runat="server" DataKeyNames="id" AutoGenerateColumns="false"
AutoGenerateDeleteButton="true" AutoGenerateEditButton="true"
OnRowDeleting="grdStudent_RowDeleting" OnRowDataBound="grdStudent_RowDataBound" OnRowEditing="EditGrid" OnRowCancelingEdit="CancelEdit" OnRowUpdating="UpdateGrid"
ForeColor="#333333" CellPadding="4" GridLines="Both" Width="90%"
class="table table-striped table-bordered table-hover" AllowPaging="True"
EnableSortingAndPagingCallbacks="false">
<AlternatingRowStyle BackColor="White" />
<EditRowStyle BackColor="#999999" BorderStyle="Solid" HorizontalAlign="Center"
VerticalAlign="Middle" />
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333"
BorderStyle="Solid" HorizontalAlign="Center" VerticalAlign="Middle" />
<SortedAscendingCellStyle BackColor="#E9E7E2" />
<SortedAscendingHeaderStyle BackColor="#506C8C" />
<SortedDescendingCellStyle BackColor="#FFFDF8" />
<SortedDescendingHeaderStyle BackColor="#6F8DAE" CssClass="table table-striped table-bordered table-hover" />
<Columns>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%#Eval("id") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="lblFirstName" runat="server" Text='<%#Eval("first_name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtFirstName" Text='<%#Eval("first_name") %>' Width="100px"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="lblLastName" runat="server" Text='<%#Eval("last_name") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtLastName" Text='<%#Eval("last_name") %>' Width="100px"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Contact No">
<ItemTemplate>
<asp:Label ID="lblContactNo" runat="server" Text='<%#Eval("phone_no") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtContactNo" Text='<%#Eval("phone_no") %>' Width="100px"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:Label ID="lblEmail" runat="server" Text='<%#Eval("email") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtEmail" Text='<%#Eval("email") %>' Width="100px"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Address">
<ItemTemplate>
<asp:Label ID="lblAddress" runat="server" Text='<%#Eval("address") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtAddress" Text='<%#Eval("address") %>' Width="100px"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<%-- <asp:BoundField DataField="active" HeaderText="IsActive" />--%>
<asp:TemplateField HeaderText="IsActive">
<ItemTemplate>
<asp:Label ID="lblIsActive" runat="server" Text='<%#Eval("active") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<select id="ddlIsActive" class="dropdown" runat="server">
<option value="1">True</option>
<option value="2">False</option>
</select>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Username">
<ItemTemplate>
<asp:Label ID="lblUsername" runat="server" Text='<%#Eval("username") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtUsername" Text='<%#Eval("username") %>' Width="100px"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Password">
<ItemTemplate>
<asp:Label ID="lblPassword" runat="server" Text='<%#Eval("password") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtPassword" Text='<%#Eval("password") %>' Width="100px"></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<%--<asp:ButtonField ButtonType="Link" --%>
</Columns>
</asp:GridView>
I need to access the delete button in Row Data bound event and add a confirmation attribute to it. I tried the below code but only Edit button is accessed at server side.
protected void grdStudent_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex != grdStudent.EditIndex)
{
string text = ((LinkButton)e.Row.Cells[0].Controls[0]).Text;
//text always has the value as "Edit" never "Delete"
if (text == "delete")
{
(e.Row.Cells[0].Controls[0] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to edit this row?');";
//del.OnClientClick = "return confirm('Are you certain you want to delete the record?');";
}
}
// (e.Row.Cells[0].Controls[0] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to edit this row?');";
// //(e.Row.Cells[0].Controls[1] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to delete this row?');";
//}
//if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowIndex == grdStudent.EditIndex)
//{
// (e.Row.Cells[0].Controls[0] as LinkButton).Attributes["onclick"] = "return confirm('Do you want to edit this row?');";
//}
}
How can I access Delete button and add a confirmation message box.
You have to add the attributes as a key/value pair.
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lbEdit = e.Row.Cells[0].Controls[0] as LinkButton;
lbEdit.Attributes.Add("onclick", "return confirm('Do you want to edit this row?');");
LinkButton lbDelete = e.Row.Cells[0].Controls[2] as LinkButton;
lbDelete.Attributes.Add("onclick","return confirm('Do you want to delete this row?');");
}
#VDWWD's answer should solve the original problem.
These days, I personally like to use icon/font to look more professional.
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewDemo.aspx.cs" Inherits="DemoWebForm.GridViewDemo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
</head>
<body>
<form id="form1" runat="server">
<br />
<div class="container">
<asp:GridView runat="server" ID="grdStudent"
AutoGenerateColumns="False"
OnRowEditing="grdStudent_RowEditing"
OnRowDeleting="grdStudent_RowDeleting"
OnRowDataBound="grdStudent_RowDataBound"
CssClass="table">
<Columns>
<asp:TemplateField HeaderText="Edit">
<ItemTemplate>
<asp:LinkButton runat="server" ID="EditLinkButton" CommandName="Edit">
<i class="fa fa-pencil"></i>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:LinkButton runat="server" ID="DeleteLinkButton" CommandName="Delete">
<i class="fa fa-trash-o"></i>
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Id" HeaderText="Id" />
<asp:BoundField DataField="Name" HeaderText="Name" />
</Columns>
</asp:GridView>
</div>
</form>
</body>
</html>
Code Behind
using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
namespace DemoWebForm
{
public partial class GridViewDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
grdStudent.DataSource = Collection;
grdStudent.DataBind();
}
}
protected void grdStudent_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var d = e.Row.FindControl("DeleteLinkButton") as LinkButton;
d.Attributes.Add("onclick", "return confirm('Do you want to delete this row?');");
}
}
protected void grdStudent_RowDeleting(object sender, GridViewDeleteEventArgs e){}
protected void grdStudent_RowEditing(object sender, GridViewEditEventArgs e){}
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
public static IList<Item> Collection = new List<Item>
{
new Item {Id = 1, Name = "One"},
new Item {Id = 2, Name = "Two"},
new Item {Id = 3, Name = "Three"}
};
}
}
This will work better for confirmation message box at Client side:
if (e.Row.RowType == DataControlRowType.DataRow)
{
// reference the Delete LinkButton
LinkButton lb = (LinkButton)e.Row.Cells[0].Controls[2];
if (lb.Text == "Delete")
{
lb.OnClientClick = "return confirm('Are you sure you want to delete this row?');";
}
}
I have a Grid Where I have Id like this:
<div class="row ">
<asp:GridView ID="gvIndex" CssClass="table table-bordered table-responsive" runat="server" AllowPaging="True" PageSize="10" AutoGenerateColumns="False" AutoGenerateEditButton="False" OnRowCommand="gvIndex_RowCommand">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Número" HtmlEncode="false"> //This is my Id Field
<FooterStyle Width="200px" />
</asp:BoundField>
<asp:BoundField DataField="Nombre" HeaderText="Nombre" HtmlEncode="false">
<FooterStyle Width="400px" />
</asp:BoundField>
<asp:BoundField DataField="Direccion" HeaderText="Dirección" HtmlEncode="false">
<FooterStyle Width="400px" />
</asp:BoundField>
<asp:BoundField DataField="Puesto" HeaderText="Puesto" HtmlEncode="false">
<FooterStyle Width="400px" />
</asp:BoundField>
<asp:BoundField DataField="Fecha" HeaderText="Fecha" HtmlEncode="false">
<FooterStyle Width="175px" />
</asp:BoundField>
<asp:BoundField DataField="CorreoElectronico" HeaderText="Correro Electrónico" HtmlEncode="false">
<FooterStyle Width="350px" />
</asp:BoundField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Edición">
<ItemTemplate>
<asp:LinkButton ID="EditarIngreso" OnClick="EditarIngreso_Click" CommandArgument="<% Eval('Id') %>" CommandName="SelectRow" CssClass="btn btn-primary" runat="server">Editar</asp:LinkButton> //There I want to get value of Id
<%--<asp:HyperLink ID="EditarIngreso" BorderStyle="None" OnClick="EditarIngreso_Click" Text="Editar" runat="server">HyperLink</asp:HyperLink>--%>
<%--<a id="EditarIngreso" runat="server" style="text-decoration: underline; border: none">Editar</a>--%>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
As you can see, I want to get value of Id in this line:
<asp:LinkButton ID="EditarIngreso" OnClick="EditarIngreso_Click" CommandArgument="<% Eval('Id') %>" CommandName="SelectRow" CssClass="btn btn-primary" runat="server">Editar</asp:LinkButton>
But I don't know what is wrong with this, I try to get it with this method:
protected void gvIndex_RowCommand(object sender, GridViewCommandEventArgs e)
{
MyID.Value = e.CommandArgument.ToString();
}
But I just receiving "<%Eval('Id') %>" instead my Id into MyID.Value
Any Help is very appreciate. Regards
You use it like this:
<asp:LinkButton ID="LinkButton1" CommandArgument='<%# Eval("Id") %>' runat="server" Text="Button" CommandName="SelectRow" />
And it looks you are using a regular button OnClick also, you need to remove that and use the CommandName in gvIndex_RowCommand
protected void gvIndex_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "SelectRow")
{
MyID.Value = e.CommandArgument.ToString();
}
}
First missing #
<asp:LinkButton ID="EditarIngreso" OnClick="EditarIngreso_Click" CommandArgument="<%# Eval('Id') %>" CommandName="SelectRow" CssClass="btn btn-primary" runat="server">Editar</asp:LinkButton>
In Gridview Tag
add DataKeyNames= "Id"
<asp:Gridview id="gvIndex" DataKeyNames= "Id" />
Then OnClick of LinkButton
protected void EditarIngreso_Click(object sender,EventArgs e)
{
LinkButton btn = sender as LinkButton ;
GridViewRow row = btn.NamingContainer as GridViewRow;
string pk = gvIndex.DataKeys[row.RowIndex].Values[0].ToString();
// here PK is your ID
// Convert it to Int32
}
I have Gridview having multiple rows with textboxes and dropdownlists... I want to insert data with values of textboxes and dropdownlist from multiple rows at a time with stored procedures. How it is possible.. pls help me,
<asp:gridview ID="Gridview1" runat="server" ShowFooter="True" AutoGenerateColumns="False" BackColor="White" BorderColor="#CCCCCC" BorderStyle="None" BorderWidth="1px" CellPadding="3">
<Columns>
<asp:BoundField DataField="RowNumber" HeaderText="Row Number" />
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:TextBox ID="txtFirstName" runat="server" CssClass="textbox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:TextBox ID="txtLastName" runat="server" CssClass="textbox"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Date">
<ItemTemplate>
<asp:TextBox ID="txtDate" runat="server" CssClass="textbox"></asp:TextBox>
</ItemTemplate></asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="ddlAgeRange" runat="server">
<asp:ListItem Value="-1">Age Range</asp:ListItem>
</asp:DropDownList>
</ItemTemplate></asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="ddlRelationship" runat="server">
<asp:ListItem Value="-1">Relationship</asp:ListItem>
</asp:DropDownList>
</ItemTemplate></asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:DropDownList ID="ddlGender" runat="server">
<asp:ListItem Value="-1">Gender</asp:ListItem>
</asp:DropDownList>
</ItemTemplate></asp:TemplateField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#000066" />
<HeaderStyle BackColor="#006699" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="White" ForeColor="#000066" HorizontalAlign="Left" />
<RowStyle ForeColor="#000066" />
<SelectedRowStyle BackColor="#669999" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#007DBB" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#00547E" />
</asp:gridview>
private void userInsert()
{
if (MessageBox.Show("Do you want to add the new data ?", "Confirm ", MessageBoxButtons.YesNo,MessageBoxIcon.Question) == DialogResult.Yes)
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
try
{
foreach (GridViewRow dRow in userDataGridView.Rows)
{
cmd.CommandText = string.Format(
"insert into users(first_name,last_name,default_rate,default_location,spi_user_id,nickname) values('{0}','{1}',{2},{3},{4},'{5}')",
userDataGridView.CurrentRow.Cells[0].Value.ToString(),
userDataGridView.CurrentRow.Cells[1].Value.ToString(),
userDataGridView.CurrentRow.Cells[2].Value.ToString(),
locationID2ComboBox.SelectedValue,
userDataGridView.CurrentRow.Cells[4].Value.ToString(),
userDataGridView.CurrentRow.Cells[5].Value.ToString());
con.Open();
cmd.ExecuteNonQuery();
}
MessageBox.Show("Your data has been added successfully ", "Saved info", ageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
userSelect();
}
}
}
I am not able to change the page index of the gridview. The server method for OnPageIndexChanging is not at all getting fired. I do not know what am I doing wrong here.
Here's my gridview
<asp:GridView ID="VideoCommentsGrid" runat="server"
OnRowDataBound="VideoCommentsGrid_RowDataBound"
OnPageIndexChanging="VideoCommentsGrid_PageIndexChanging" allowpaging="true"
CssClass="tables"
EmptyDataText="<div class='notice show bottom'>No Comments found.</div>"
AutoGenerateColumns="False" >
<Columns>
<asp:TemplateField HeaderStyle-HorizontalAlign="center" HeaderStyle-Width="70" ItemStyle-HorizontalAlign="center">
<HeaderTemplate>
Approve
<br />
<input id="ChkAllApprovedItems" type="checkbox" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkApproval" Checked='<%#Eval("IsApproved").ToString()=="1"?true:false %>' runat="server" />
<asp:Label ID="lblCommentID" runat="server" Text='<%#Eval("CommentId") %>' CssClass="hide"/>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderStyle-HorizontalAlign="center" HeaderStyle-Width="70" ItemStyle-HorizontalAlign="center">
<HeaderTemplate>
Reject
<br />
<input id="ChkAllRejectedItems" type="checkbox" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkReject" Checked='<%#Eval("IsRejected").ToString()=="1"?true:false %>' runat="server" />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" />
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:TemplateField HeaderText="User Name" HeaderStyle-Width="70" >
<ItemTemplate>
<asp:Label ID="lblUserName" runat="server" Text='<%#Eval("FirstName")%>'> </asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" Width="150" />
<ItemStyle HorizontalAlign="Left" CssClass="wordWrap" Width="150" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Comments" HeaderStyle-Width="70" >
<ItemTemplate>
<asp:Label ID="lblComment" runat="server" Text='<%#Eval("VideoComment") %>' />
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" Width="150" />
<ItemStyle HorizontalAlign="Left" CssClass="wordWrap" Width="150" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Comment Time* ">
<ItemTemplate>
<asp:Label ID="lblCommentDate" runat="server" Text='<%#(Eval("CommentCreatedDate"))%>'> </asp:Label>
</ItemTemplate>
<HeaderStyle HorizontalAlign="Center" Width="80" />
<ItemStyle HorizontalAlign="Center" Width="80" />
</asp:TemplateField>
</Columns>
<HeaderStyle Height="30" />
<PagerStyle HorizontalAlign="Center" CssClass="footer" />
<AlternatingRowStyle CssClass="odd" />
</asp:GridView>
My server side code is as follows,
protected void Page_Load(object sender, EventArgs e)
{
LoadCommentsGridView(VideoCommentsGrid.PageIndex);
}
protected void VideoCommentsGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (!e.Row.RowType.Equals(DataControlRowType.DataRow)) return;
}
protected void VideoCommentsGrid_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
VideoCommentsGrid.PageIndex = e.NewPageIndex;
LoadCommentsGridView(VideoCommentsGrid.PageIndex);
hidCheckedValue.Value = string.Empty;
}
protected void LoadCommentsGridView(int PageIndex)
{
SetPageIndex(PageIndex);
LoadDefaultGrid();
}
private void LoadDefaultGrid()
{
VideoCommentsGrid.PageSize = CurrentSchoolDetails.PageViewCount;
IList<Comment> allComments = CommentRepository.GetAllCommentsByVideoID(VideoID);
BindDataControls.BindGridView(VideoCommentsGrid, allComments);
}
Please help me out,
Thanks.
I think this is occurring because you are binding the data to the GridView on every page load, where as you only need to bind the data once initially and then again when the page index changes.
Try changing the code in the Page_Load method like so:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
LoadCommentsGridView(VideoCommentsGrid.PageIndex);
}
}
on the rowdatabound method try to comment this piece of code and see what happen.
//if (!e.Row.RowType.Equals(DataControlRowType.DataRow)) return;
I have two imagebuttons which are associated with a modalpopupextender. When I click imagebutton1, it opens up the panel and within that panel there is a grid which loads with the information. However, when I click Imagebutton2 it opens up the panel but does not display the gridview even though that gridview tag is under that panel.
I am pretty new with web, please help. Thank You. Please find the code below:
<asp:Panel ID="PNL" ScrollBars="Auto" runat="server" Style="border: 2px solid Black; display: none; width: auto;
background-color: White; padding: 20px; text-align: center;" Height="444">
<asp:Label ID="LabelCount" runat="server" Text="Label" Font-Size="Large"
style="text-align: center"></asp:Label>
<asp:Button ID="ButtonOK" Text="OK" runat="server" />
<%-- Area for keeping POPUP grid ot window or picture DO NOT PUT UNDER TABLE Taj 3-Jan-2010--%>
<asp:GridView ID="gvUsersWHYME" runat="server" BackColor="White" BorderColor="#010101"
BorderStyle="None" CaptionAlign="Top" CellPadding="1" CellSpacing="2" GridLines="None"
Style="margin-left: 0px" DataSourceID="SqlDataSource0" AutoGenerateColumns="False"
EnableTheming="False" AllowSorting="True"
OnRowDataBound="gvUsers_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Roles" Visible="False">
<HeaderTemplate>
<asp:CheckBox ID="chkAll" runat="server"
onclick="javascript:SelectAllCheckboxesSpecific(this);" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkGenerate" runat="server"
onclick="javascript:HighlightRow(this);" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ProjectNum" HeaderText="Release#" SortExpression="ProjectNum"
ReadOnly="true" />
<asp:BoundField DataField="IPMRefNum" HeaderText="IPM Ref #"
SortExpression="IPMRefNum" />
<asp:BoundField DataField="TestprojectNo" HeaderText="Release Description" SortExpression="TestprojectNo"
ItemStyle-Width="444">
<ItemStyle Width="444px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="ProjectName" HeaderText="ProjectName" SortExpression="ProjectName"
Visible="False" />
<asp:BoundField DataField="ProposedPhaseName" HeaderText="Proposed Phase Name" ItemStyle-Wrap="False"
SortExpression="ProposedPhaseName">
<ItemStyle Wrap="False"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="DependencyList" HeaderText="Dependency List"
SortExpression="DependencyList" />
<asp:BoundField DataField="QA_Planned_EndDate" HeaderText="Release Handover Date"
SortExpression="QA_Planned_EndDate" DataFormatString="{0:d}"
ItemStyle-Wrap="False">
<ItemStyle Wrap="False"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="Applications" HeaderText="Impacted Application(s)"
SortExpression="Applications" />
<asp:BoundField DataField="AppCount" HeaderText="Count"
SortExpression="AppCount" />
</Columns>
<FooterStyle BackColor="White" ForeColor="#330099" />
<RowStyle BackColor="White" ForeColor="#330099" />
<HeaderStyle BackColor="#ACCDF6" Font-Bold="True" ForeColor="#FFFFCC" />
</asp:GridView>
<asp:Label ID="lblCountImpacted" runat="server" Text="Total Impacted App."
Font-Size="Large"></asp:Label>
</asp:Panel>
<br />
<br />
<br />
<br />
<br />
<asp:Panel ID="Panel1" ScrollBars="Auto" runat="server" Style="border: 2px solid Black; display: none; width: auto;
background-color: White; padding: 20px; text-align: center;" Height="444">
<asp:Button ID="Button1" Text="OK" runat="server" />
<asp:GridView ID="GridView4" runat="server" BackColor="White" BorderColor="#010101"
BorderStyle="None" CaptionAlign="Top" CellPadding="1" CellSpacing="2" GridLines="None"
Style="margin-left: 0px" DataSourceID="SqlDataSource6" AutoGenerateColumns="False"
EnableTheming="False" AllowSorting="True"
OnRowDataBound="GridView4_RowDataBound">
<Columns>
<asp:BoundField DataField="ProjectNum" HeaderText="Release#" SortExpression="ProjectNum"
ReadOnly="true" />
<asp:BoundField DataField="IPMRefNum" HeaderText="IPM Ref #"
SortExpression="IPMRefNum" />
<asp:BoundField DataField="TestprojectNo" HeaderText="Release Description" SortExpression="TestprojectNo"
ItemStyle-Width="444">
<ItemStyle Width="444px"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="ProjectName" HeaderText="ProjectName" SortExpression="ProjectName"
Visible="False" />
<asp:BoundField DataField="ProposedPhaseName" HeaderText="Proposed Phase Name" ItemStyle-Wrap="False"
SortExpression="ProposedPhaseName">
<ItemStyle Wrap="False"></ItemStyle>
</asp:BoundField>
<asp:BoundField DataField="DependencyList" HeaderText="Dependency List"
SortExpression="DependencyList" />
<asp:BoundField DataField="QA_Planned_EndDate" HeaderText="Release Handover Date"
SortExpression="QA_Planned_EndDate" DataFormatString="{0:d}"
ItemStyle-Wrap="False">
<ItemStyle Wrap="False"></ItemStyle>
</asp:BoundField>
</Columns>
<FooterStyle BackColor="White" ForeColor="#330099" />
<RowStyle BackColor="White" ForeColor="#330099" />
<HeaderStyle BackColor="#ACCDF6" Font-Bold="True" ForeColor="#FFFFCC" />
</asp:GridView>
</asp:Panel>
I have created a sample code.Similar to your problem.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="MasterDetail.aspx.cs"
Inherits="MasterDetail" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxtoolkit" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form" runat="server">
<asp:ScriptManager ID="scriptManager" runat="server" />
<div>
<asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblTitle" runat="server" Text="Customers" BackColor="lightblue" Width="95%" />
<asp:GridView ID="gvCustomers" runat="server" DataKeyNames="Id" AutoGenerateColumns="false"
AllowPaging="true" AllowSorting="true" PageSize="10" Width="95%">
<AlternatingRowStyle BackColor="aliceBlue" />
<HeaderStyle HorizontalAlign="Left" />
<Columns>
<asp:TemplateField ControlStyle-Width="50px" HeaderStyle-Width="60px">
<ItemTemplate>
<asp:Button ID="btnViewDetails" runat="server" Text="Details" OnClick="BtnViewDetails_Click" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Id" HeaderText="ID" SortExpression="Id" ReadOnly="true" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="contactname" ReadOnly="true" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button ID="btnShowPopup" runat="server" Style="display: none" />
<ajaxtoolkit:ModalPopupExtender ID="mdlPopup" runat="server" TargetControlID="btnShowPopup"
PopupControlID="pnlPopup" CancelControlID="btnClose" BackgroundCssClass="modalBackground" />
<asp:Panel ID="pnlPopup" runat="server" Width="500px" Style="display: none">
<asp:UpdatePanel ID="updPnlCustomerDetail" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblCustomerDetail" runat="server" Text="Customer Detail" BackColor="lightblue"
Width="95%" />
<asp:DetailsView ID="dvCustomerDetail" runat="server" DefaultMode="Edit" Width="95%"
BackColor="white" />
</ContentTemplate>
</asp:UpdatePanel>
<div align="right" style="width: 95%">
<asp:Button ID="btnSave" runat="server" Text="Save"
OnClientClick="alert('Sorry, but I didnt implement save '); return false;"
Width="50px" />
<asp:Button ID="btnClose" runat="server" Text="Close" Width="50px" />
</div>
</asp:Panel>
</div>
</form>
</body>
</html>
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class MasterDetail : System.Web.UI.Page
{
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
ds = Data();
if (!this.IsPostBack)
{
if (Session["parent"] == null)
{
gvCustomers.DataSource = ds.Tables["Parent"];
gvCustomers.DataBind();
}
else
{
gvCustomers.DataSource = Session["Parent"] as DataTable;
gvCustomers.DataBind();
}
}
}
private DataSet Data()
{
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Rows.Add(new object[] { 1, "aaaa" });
dt.Rows.Add(new object[] { 2, "bbbb" });
dt.Rows.Add(new object[] { 3, "cccc" });
dt.TableName = "Parent";
DataTable dtc = new DataTable();
dtc.Columns.Add("Id", typeof(int));
dtc.Columns.Add("Qul", typeof(string));
dtc.Rows.Add(new object[] { 1, "aaaa" });
dtc.Rows.Add(new object[] { 2, "bbbb" });
dtc.Rows.Add(new object[] { 3, "bbbb" });
dtc.TableName = "Child";
DataSet ds = new DataSet();
ds.Tables.Add(dt);
ds.Tables.Add(dtc);
Session["Parent"] = dt;
return ds;
}
protected void BtnViewDetails_Click(object sender, EventArgs e)
{
// get the gridviewrow from the sender so we can get the datakey we need
Button btnDetails = sender as Button;
GridViewRow row = (GridViewRow)btnDetails.NamingContainer;
// extract the id from the row whose details button originated the postback.
// grab the customerid and feed it to the customer details datasource
// finally, rebind the detailview
DataView dv = new DataView(ds.Tables["Child"]);
dv.RowFilter = "Id=" + Convert.ToString(this.gvCustomers.DataKeys[row.RowIndex].Value);
dvCustomerDetail.DataSource = dv;
dvCustomerDetail.DataBind();
// update the contents in the detail panel
this.updPnlCustomerDetail.Update();
// show the modal popup
this.mdlPopup.Show();
}
}