I have a gridview like below:
<asp:GridView ID="gvitems" runat="server" AutoGenerateColumns="false" CssClass="GridStyle" AllowSorting="true" OnSorting="OnSorting" DataKeyNames="Id" OnRowCommand="gv_RowCommand"
OnRowEditing="gv_RowEditing" OnRowUpdating="gv_RowUpdating" OnRowCancelingEdit="gv_RowCancelEdit" >
<Columns>
<asp:buttonfield buttontype="Link"
commandname="View"
text="View"/>
<asp:TemplateField>
<ItemTemplate>
<asp:Button runat="server" Text="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button runat="server" Text="Update" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Next Steps">
<ItemTemplate>
<asp:Label runat="server" ID="lblNextSteps" Text='<%# Eval("NextSteps")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox runat="server" ID="txtNextSteps" Text='<%# Eval("NextSteps")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox runat="server" ID="txtNextStepsFooter"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
And in the backend, this is how i fill it with data:
DataSet dataSet = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid_SubmittedProjects();
}
}
private void BindGrid_SubmittedProjects(string sortExpression = null)
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["ProjectsDataBase"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("ViewProjects", con))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#UserName", SqlDbType.VarChar).Value = "myusername";
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
dataSet = new DataSet();
sda.Fill(dataSet, "Project");
}
gvitems.DataSource = dataSet.Tables[0].DefaultView;
gvitems.DataBind();
}
}
}
When I click on the "View" hyperlink on each row, it works, so OnRowCommand function below is triggered.
protected void gv_RowCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
//my work
}
}
However, when I click on "Edit" button, nothing is happening, OnRowEditing is not being triggered.
protected void gv_RowEditing(Object sender, GridViewEditEventArgs e)
{
gvitems.EditIndex = e.NewEditIndex;
this.BindGrid_SubmittedProjects();
}
protected void gv_RowUpdating(Object sender, GridViewUpdateEventArgs e)
{
//my update query.
}
I could not see what I am doing wrong. Tried many things I've found over online but none worked. Any help would be so appreciated.
Regards.
Using LinkButton instead of regular button fixed the issue.
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton Text="Edit" runat="server" CommandName="Edit" />
<asp:LinkButton Text="Delete" runat="server" CommandName="Delete" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton Text="Update" runat="server" CommandName="Update" />
<asp:LinkButton Text="Cancel" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
Related
Here is my aspx file content.
<asp:UpdatePanel ID="UpdatePanel1" runat="server" OnUnload="UpdatePanel_Unload">
<ContentTemplate>
<table>
<tr>
<td>
<input id="hdnAID" type="hidden" runat="server" />
<asp:GridView ID="GridView1" runat="server" OnRowCancelingEdit="GridView1_RowCancelingEdit"
OnRowEditing="GridView1_RowEditing" OnRowUpdating="GridView1_RowUpdating" OnRowDataBound="GridView1_RowDataBound" OnDataBound="GridView1_DataBound"
DataKeyNames="GeneralSettingID" EnableViewState="true">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<GridEditPopupMenu:GridEditPopupMenu ID="GridEditPopupMenu1" runat="server" currenttemplate="ItemTemplate" ShowDeleteLink="0" />
</ItemTemplate>
<EditItemTemplate>
<GridEditPopupMenu:GridEditPopupMenu ID="GridEditPopupMenu1" runat="server" currenttemplate="EditItemTemplate" />
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="GeneralSettingID" HeaderText="SettingNo" ReadOnly="true" />
<asp:TemplateField HeaderText="SettingName">
<ItemTemplate>
<asp:Label ID="Label25" runat="server" Text='<%# Eval("GeneralSettingName") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtUpdateGeneralSettingName" onfocus="this.blur();" runat="server" Text='<%# Bind("GeneralSettingName") %>'
Width="350px" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Values">
<ItemTemplate>
<asp:Label ID="Label23" runat="server" Text='<%# Eval("GeneralSettingValue") %>' />
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtUpdateGeneralSettingValue" runat="server" Text='<%# Bind("GeneralSettingValue") %>'
Width="600px" TextMode="MultiLine" Rows="6" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Company1">
<ItemTemplate>
<asp:Label ID="Label28" runat="server" Text='<%# Eval("GeneralSettingCompany") %>' />
</ItemTemplate>
<ItemTemplate>
<asp:TextBox ID="txtUpdateGeneralSettingCompany" runat="server" Text='<%# Bind("GeneralSettingCompany") %>'
Width="100px" TextMode="MultiLine" Rows="1" Enabled="false" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Company2">
<ItemTemplate>
<asp:DropDownList ID="drpCompanyList" runat="server" AutoPostBack="true" OnSelectedIndexChanged="drpCompanyList_SelectedIndexChanged" DataTextField="CompanyName" DataValueField="CompanyID"></asp:DropDownList>
<input id="hdnCompanyId" type="hidden" value='<%# Eval("GeneralSettingCompany") %>' runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</td>
</tr>
</table>
</ContentTemplate>
</asp:UpdatePanel>
Here is the .cs side .
private LMSDataAccess.LookupsDataContext LkpDC = new LMSDataAccess.LookupsDataContext(ConfigFile.DBConnStr);
private System.Collections.Generic.List<LMSDataAccess.GeneralSetting> GeneralSettingList = null;
protected void Page_Load(object sender, EventArgs e)
{
base.ModuleID = 27;
if (!IsPostBack)
{
if (Request["AID"] != null)
hdnAID.Value = Request["AID"];
BindData();
}
}
private void BindData()
{
GeneralSettingList = LkpDC.GeneralSettingsGetAll(Common.NVLInt(hdnAID.Value),null).ToList();
GridView1.DataSource = GeneralSettingList;
GridView1.DataBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindData();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindData();
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox txtUpdateGeneralSettingName = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtUpdateGeneralSettingName");
TextBox txtUpdateGeneralSettingValue = (TextBox)GridView1.Rows[e.RowIndex].FindControl("txtUpdateGeneralSettingValue");
var hdnCompany = (HiddenField)GridView1.Rows[e.RowIndex].FindControl("hdnCompanyId") as HiddenField;
string KeyValue = GridView1.DataKeys[e.RowIndex].Value.ToString();
LkpDC.GeneralSettingsUpdate(Convert.ToInt32(KeyValue),
txtUpdateGeneralSettingName.Text,
txtUpdateGeneralSettingValue.Text,
Convert.ToInt32(hdnCompany.Value));
GridView1.EditIndex = -1;
BindData();
ResultCode = 0;
}
protected List<LMSDataAccess.Company> GetAllCompanies()
{
System.Collections.Generic.List<LMSDataAccess.Company> CompanyList = null;
LMSDataAccess.OrganizationDataContext OrgDC = new LMSDataAccess.OrganizationDataContext(ConfigFile.DBConnStr);
CompanyList = OrgDC.CompaniesGetAll(null).ToList();
return CompanyList;
}
protected void drpCompanyList_SelectedIndexChanged(object sender, EventArgs e)
{
DropDownList ddl = (DropDownList)sender;
GridViewRow row = (GridViewRow)ddl.Parent.Parent;
var hdnCompany = row.FindControl("hdnCompanyId") as HiddenField;
hdnCompany.Value = ddl.SelectedValue;
}
protected void GridView1_RowDataBound(object sender,GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
var ddl = e.Row.FindControl("drpCompanyList") as DropDownList;
//here is the problem.
var hdn = e.Row.FindControl("hdnCompanyId") as HiddenField;
if (ddl != null)
{
ddl.DataSource = GetAllCompanies();
ddl.DataValueField = "CompanyID";
ddl.DataTextField = "CompanyName";
ddl.DataBind();
}
}
}
My beloved problem is not being able to get hdnCompanyId element when GridView1_RowDataBound and drpCompanyList_SelectedIndexChangedfired.I am always getting null.(as showed at the commented line )
I have tried under GridView1_RowDataBound event method like e.Row.FindControl("hdnCompanyId")
but it did not work.
My final aim is to setting and getting this element to control selected items of my dropdownlist.
I think the code is well written but I guess I am missing something about hierarchy of the user control elements.
Can you help me about what I am missing?
I have found that the problem was choosing the wrong casting type of the input.It must be HtmlInputHidden rather than HiddenField.I hope someone can get useful info from that question.
Here is my code for updating the gridview rows. But what it does it shows this behavior which I guess is not what it usually does. Please point out what did I do wrong.
This is an image showcasing what is happening.
The code:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
bindgrid();
}
}
private void bindgrid()
{
con.Open();
MySqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from vendor";
MySqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
bindgrid();
}
And this is ASPX code:
<asp:TemplateField>
<ItemTemplate>
<asp:Button Text="Edit Element" CssClass="btn btn-success fa fa-edit" ID="Editbutton" runat="server" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:Button Text="Update" CssClass="btn btn-success fa fa-edit" ID="updatebutton" runat="server" CommandName="Update" />
<asp:Button Text="Cancel" CssClass="btn btn-warning fa fa-close" ID="cancelbutton" runat="server" CommandName="Cancel" />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Vendor ID">
<ItemTemplate>
<asp:Label ID="idlbl" runat="server" Text='<%# Eval("v_id")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="idtext" runat="server" Text='<%# Eval("v_id")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Vendor Name">
<ItemTemplate>
<asp:Label ID="namelbl" runat="server" Text='<%# Eval("v_name")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="nametext" runat="server" Text='<%# Eval("v_name")%>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
I want to update only selected row from my grid view when i press linked button but it is not working on my end .
Here is my Design Page
<asp:GridView ID="grdCompanyUsers" runat="server"
DataKeyNames="id_company_user,nm_company_username"
AutoGenerateColumns="false" GridLines="None" CssClass="grid" AlternatingRowStyle-
BackColor="#DDE0EF" OnRowDataBound="grdCompanyUsers_DataBound">
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="~/Images
/Cancel.jpg" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="CompUserID" runat="server" Width="15"
Text='<%#Eval("id_company_user")%>'> </asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="companyusername" runat="server" Width="51"
Text='<%#Eval("nm_company_username")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="compName" runat="server" Width="56" Text='<%#Eval("nm_company_name")%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="compDesc" runat="server" Width="129" Text='<%#Eval("nm_company_desc")%>'>
</asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="compEmail" runat="server" Width="103px"
Text='<%#Eval("nm_company_email_address")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="compAddress" runat="server" Width="153px"
Text='<%#Eval("nm_company_address")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkBoxStatus" runat="server" Width="15px" Enabled="false"
Text='<%#Eval("ind_active")%>'>
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" Font-Underline="false"
CommandArgument='<%#Eval ("id_company_user")%>'
OnClick="btnEdit_Click">Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lnkDeny" Font-Underline="false" CommandName="Deny"
CommandArgument='<%# Eval("id_company_user") %>'
OnClick="btnDeny_Click">Deny</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is my code behind the aspx page
protected void btnEdit_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)sender;
GridViewRow row = (GridViewRow)btn.NamingContainer;
int i = Convert.ToInt32(row.RowIndex);
_connString = ConfigurationManager.AppSettings["connString"];
using (SqlConnection conn = new SqlConnection(_connString))
{
conn.Open();
SqlCommand cmd = new SqlCommand("update ref_registration_company_user
set ind_active=1 where id_company_user=id_company_user", conn);
cmd.ExecuteNonQuery();
conn.Close();
}
}
Here is Design View :
I just want that only selected row should be affected in database.
I will be thank full for help.
you need to set the id_company_user value in your sql statement. use parameters as below.
SqlCommand cmd = new SqlCommand("update ref_registration_company_user set ind_active=1 where id_company_user=#id_company_user", conn);
cmd.Parameters.AddWithValue("#id_company_user", id);
you need to get current row id_company_user value check below SO question and answer, you can use
OnRowCommand of GridView and CommandArgument property
GridView: Get datakey of the row on button click
<asp:GridView ID="grdCompanyUsers" runat="server" DataKeyNames="id_company_user,nm_company_username" AutoGenerateColumns="false" GridLines="None" CssClass="grid" AlternatingRowStyle-BackColor="#DDE0EF" OnRowDataBound="grdCompanyUsers_DataBound"
OnRowCommand="myGridView_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="btnEdit" runat="server" Font-Underline="false" CommandArgument='<%#Eval ("id_company_user")%>' CommandName="Edit">Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
code-behind:
protected void myGridView_RowCommand(object sender, GridViewCommandEventArgs e)
{
var id= int.Parse(e.CommandArgument);
_connString = ConfigurationManager.AppSettings["connString"];
using (SqlConnection conn = new SqlConnection(_connString))
{
conn.Open();
using(SqlCommand cmd = new SqlCommand("update ref_registration_company_user set ind_active=1 where id_company_user=id_company_user", conn))
{
cmd.Parameters.AddWithValue("#id_company_user", id);
cmd.ExecuteNonQuery();
}
}
}
Can you please check once your update query where clause,
Check the sqlDataSource control for this problem, you can add the select and update command for populate and update rows your GridView on there.
Maybe this example could be you useful
http://asp-net-example.blogspot.mx/2008/12/aspnet-gridview-and-sqldatasource.html
I have a GridView with a button which sets all rows into edit mode (which is what I want). However I was wondering if there is a way to create a button that will update the whole gridview with my changes. Here is the code behind this.
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="False"
onrowcommand="gvUsers_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="labelID" Visible="false">
<ItemTemplate>
<asp:Label ID="ID" runat="server" Text='<%# Eval("id") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="First Name">
<ItemTemplate>
<asp:Label ID="labelfirstname" Visible='<%# !(bool) IsInEditMode %>' runat="server" Text='<%# Eval("firstname") %>' />
<asp:TextBox ID="txtFirstName" Visible='<%# IsInEditMode %>' runat="server" Text='<%# Eval("firstname") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Last Name">
<ItemTemplate>
<asp:Label ID="labellastname" Visible='<%# !(bool) IsInEditMode %>' runat="server" Text='<%# Eval("lastname") %>' />
<asp:TextBox ID="txtLastName" Visible='<%# IsInEditMode %>' runat="server" Text='<%# Eval("lastname") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Button1" runat="server" Text="Edit Mode" onclick="Button1_Click1" />
<asp:Button ID="Button2" runat="server" Text="View Mode" onclick="Button2_Click1" />
And here is the c#
private bool isEditMode = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
string connectiongString = "Data Source=WSCJTCSQ1;Initial Catalog=LiquorStore;Integrated Security=True";
SqlConnection myConnection = new SqlConnection(connectiongString);
SqlDataAdapter ad = new SqlDataAdapter("SELECT id, firstname, lastname, nickname FROM Company", myConnection);
DataSet ds = new DataSet();
ad.Fill(ds);
gvUsers.DataSource = ds;
gvUsers.DataBind();
}
protected bool IsInEditMode
{
get { return this.isEditMode; }
set { this.isEditMode = value; }
}
protected void gvUsers_RowDataBound(object sender, GridViewCommandEventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
isEditMode = true;
BindData();
}
protected void Button2_Click1(object sender, EventArgs e)
{
isEditMode = false;
BindData();
}
Thank you in advance!!
You can iterate thru you rows and get values in a textbox for specific row
foreach (GridViewRow row in gvUsers.Rows)
{
TextBox txtFirstName = row.FindControl("txtFirstName") as TextBox;
TextBox txtLastName = row.FindControl("txtLastName") as TextBox;
if (txtFirstName.Text!="" && txtLastName.Text!="")
{
// do what you need with values
}
}
i am binding the values to gridview like this
<asp:GridView ID="grdViewAttachment_Client" runat="server" Width="615px" AutoGenerateColumns="False" GridLines="None" CssClass="grid-view" OnRowCommand="grdViewAttachment_Client_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Attachment" HeaderStyle-CssClass="hedding2">
<ItemTemplate>
<asp:LinkButton ID="lnkbtnAttachments" runat="server" Text="Delete" CommandName="Delete" CommandArgument='<%#Eval("AttachmentId") %>' ></asp:LinkButton>
</ItemTemplate>
<HeaderStyle/>
</asp:TemplateField>
<asp:TemplateField HeaderText="Attachment" HeaderStyle-CssClass="hedding2">
<ItemTemplate>
<%--<asp:LinkButton ID="lnkbtnAttachments" runat="server" Text='<%#Eval("AttachmentName") %>' CommandName='<%#Eval("AttachmentName")%>' CommandArgument='<%#Eval("AttachmentId") %>'></asp:LinkButton>--%>
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%#Eval("AttachmentName") %>' CommandName='<%#Eval("AttachmentName")%>' ></asp:LinkButton>
</ItemTemplate>
<HeaderStyle/>
</asp:TemplateField>
<asp:TemplateField HeaderText="AssignedTo" HeaderStyle-CssClass="hedding2">
<ItemTemplate>
<asp:Label ID="lblAssignedTo" Text='<%#Eval("AssignedTo") %>' runat="server" CssClass="body-text"></asp:Label>
</ItemTemplate>
<HeaderStyle />
</asp:TemplateField>
<asp:TemplateField HeaderText="CreationDate" HeaderStyle-CssClass="hedding2">
<ItemTemplate>
<asp:Label ID="lblCreationDate" Text='<%#Eval("CreationDate") %>' runat="server" CssClass="body-text"></asp:Label>
</ItemTemplate>
<HeaderStyle />
</asp:TemplateField>
</Columns>
</asp:GridView>
In my row command event i write as follows code
protected void grdViewAttachment_Client_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection m_Conn = new SqlConnection(Utilities.ConnectionString());
SqlCommand m_oCmd;
int iStID = int.Parse(e.CommandArgument.ToString());
int pk = 0;
int.TryParse(e.CommandArgument as string, out pk);
string strStoreProcName = null;
DataSet oDS1 = new DataSet();
if (e.CommandName == "Delete")
{
strStoreProcName = StoredProcNames.Attachments_uspDeleteAttachs;
m_oCmd = new SqlCommand(strStoreProcName, m_Conn);
m_oCmd.CommandType = CommandType.StoredProcedure;
m_oCmd.Parameters.Add("#AttachmentId", SqlDbType.Int).Value = Convert.ToInt32(e.CommandArgument.ToString());
m_Conn.Open();
m_oCmd.ExecuteNonQuery();
AttachmentDetails();
}
string fname = e.CommandName.ToString();
}
But i am not getting the value i am getting the exception as Input string was not in correct format can any one help me
es #Muhammad Akhtar was right .It should be like
int iStID = Convert.ToInt32(gridName.DataKeys[Convert.ToInt32(e.CommandArgument.ToString())].Value);
Specify Datakey property in your data grid . and you can access the data key value of the current row as above
add datakey name to your statement
ID_COLUMN should be a column from data table which you are binding to gridview
Write this code for row Created
protected void grdViewAttachment_Client_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkbtnAttachments=(LinkButton)e.Row.FindControl("lnkbtnAttachments");
lnkbtnAttachments.CommandArgument = e.Row.RowIndex.ToString();
// similarly write for other controls
}
}
Do not use Delete standard commandName otherwise you have to handle the "RowDeleting" event.
Take a look at this sample:
.aspx markup
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
onrowcommand="GridView1_RowCommand">
<Columns>
<asp:TemplateField>
<ItemTemplate>
Data :
<asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<asp:LinkButton ID="btnDelete" runat="server"
CommandArgument='<%# Eval("No") %>' CommandName="Del">Delete</asp:LinkButton>
<asp:LinkButton ID="btnShow" runat="server" CommandArgument='<%# Eval("No") %>'
CommandName="Show">Show</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code behind
public class Data
{
public int No { get; set; }
public string Name { get; set; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<Data> list = new List<Data>()
{
new Data(){ No=1, Name="A"},
new Data(){ No=2, Name="B"},
new Data(){ No=3, Name="C"}
};
GridView1.DataSource = list;
GridView1.DataBind();
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Del")
{
Response.Write("Delete : " + e.CommandArgument);
}
else
if (e.CommandName == "Show")
{
Response.Write("Show : " + e.CommandArgument);
}
}
As you are not passing command Argument this will always give null reference . Try this in your control where ever you required.
<asp:LinkButton ID="LinkButton1" runat="server" Text='<%#Eval("AttachmentName") %>' CommandName='<%#Eval("AttachmentName")%>' CommandArgument='<%#Eval("AttachmentId") %>'>
<ItemTemplate>
<asp:LinkButton ID="lnkDetails" runat="server" CommandName="Details" CommandArgument='<%#Eval("ID")%>'
ToolTip="View Details">View</asp:LinkButton>
</ItemTemplate>
protected void gvmain_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Details")
{
int id = Convert.ToInt32(e.CommandArgument);
Response.Redirect("~/MEMBER/UploadedDocList.aspx?id=" + id, false);
}
}