I have a webform with a gridview. The first column has a button "Update" and "Delete". What I want is when I click the delete button code gets the id which was in my 3rd column.
Using the below code I only get "1"
if (e.CommandName == "Delete")
{
int id = Convert.ToInt32(e.CommandArgument);
GridViewRow row = GridView1.Rows[id];
Add_update delete = new Add_update();
delete.deleteVehicle(Convert.ToInt32(id));
reload();
}
It is not good practice use CommandArgument to target on the Row by index, because rows order can be changed by sorting for instance.
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
var dataObjects = new List<DataObject>();
for (int i = 0; i < 100; i++)
{
dataObjects.Add(new DataObject() { Index = i });
}
gridView1.DataSource = dataObjects;
gridView1.DataBind();
}
}
protected void gridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
var dataObjectIndex = int.Parse((string) e.CommandArgument);
e.Handled = true;
}
}
}
public class DataObject
{
public int Index { get; set; }
}
<asp:GridView ID="gridView1" runat="server" OnRowCommand="gridView1_RowCommand" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Index" HeaderText="Index" />
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="btnDelete" runat="server" CommandName="Delete" CommandArgument='<%# Bind("Index") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Related
Hi I have a GridView control and in it a TextBox control inside an EditItemTemplate Field.
Now I need to change the textbox text when the user enters the edit mode.
When I run the program the textbox will take the value of the label that was in the ItemTemplate and I cant access the textbox.
.aspx:
<asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="False"
ShowHeader="False" onrowcommand="GridView1_RowCommand"
onrowediting="GridView1_RowEditing" OnRowCancelingEdit="GridView1_Cancel"
onrowupdating="GridView1_RowUpdating" onrowdeleting="GridView1_RowDeleting"
onrowdatabound="GridView1_RowDataBound" DataKeyNames="TweetID">
<Columns>
<asp:TemplateField HeaderText="ProfilePicture">
<ItemTemplate>
<asp:ImageButton ID="ProfileImage" runat="server" CommandName="Redirect"
CommandArgument='<%# Container.DataItemIndex %>' Height="40px" Width="40px" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FullName">
<ItemTemplate>
<asp:label ID="FullNameLabel" runat="server" text='<%#Eval("FullName") %>'></asp:label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserName">
<ItemTemplate>
<asp:Label ID="UserNameLabel" runat="server" Text='<%#Eval("UserName") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Tweet">
<ItemTemplate>
<%--<asp:Label ID="TweetLabel" runat="server" Text='<%#Eval("TweetText") %>'></asp:Label>--%>
<asp:Label ID="TweetLabel" runat="server" Text=""></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TweetTB" runat="server" Text='<%#Eval("TweetText") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Picture">
<ItemTemplate>
<asp:Image ID="TweetPic" runat="server"
ImageUrl='<%#"~/UploadedImages/"+Eval("PicName") %>' Height="125px" Width="222px" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ReTweet">
<ItemTemplate>
<asp:ImageButton ID="ReTweetImgBTN" runat="server"
ImageUrl="~/SrcImage/retweet-action.png" Height="27px" Width="29px"
CommandName="ReTweet" CommandArgument='<%# Container.DataItemIndex %>'/>
<%--<asp:Label ID="ReTweetEd" runat="server" Text="ReTweetEd" Visible="false"></asp:Label>--%>
<%--<asp:Button ID="ReTweetBTN" runat="server" Text="ReTweet" CommandName="ReTweet" CommandArgument='<%# Container.DataItemIndex %>' />--%>
<asp:Label ID="ReTweetStat" runat="server" Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Like">
<ItemTemplate>
<asp:ImageButton ID="LikeImgBTN" runat="server" ImageUrl="~/SrcImage/like-action.png"
Height="27px" Width="29px" CommandName="Like" CommandArgument='<%# Container.DataItemIndex %>'/>
<%--<asp:Button ID="LikeBTN" runat="server" Text="Like" CommandName="Like" CommandArgument='<%# Container.DataItemIndex %>' />--%>
<asp:Label ID="LikeStat" runat="server" Visible="false"></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Options">
<ItemTemplate>
<asp:LinkButton ID="Edit" runat="server" Text="Edit" CommandName="Edit" />
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="Delete" runat="server" Text="Delete" CommandName="Delete" />
<asp:LinkButton ID="btn_Update" runat="server" Text="Update" CommandName="Update"/>
<asp:LinkButton ID="btn_Cancel" runat="server" Text="Cancel" CommandName="Cancel"/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="TweetID" Visible="false">
<ItemTemplate>
<asp:HiddenField ID="TweetID" runat="server" Value='<%#Eval("TweetID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="UserID" Visible="false">
<ItemTemplate>
<asp:HiddenField ID="UserID" runat="server" Value='<%#Eval("UserID") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs:
protected void Page_Load(object sender, EventArgs e)
{
Session["UserID"] = 1; // To be removed
if(!IsPostBack)
BindGridview();
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
int userId = int.Parse(Session["UserID"].ToString());
if (e.CommandName == "Like")
{
int index = Convert.ToInt32(e.CommandArgument);
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(GridView1.DataKeys[index].Value.ToString())))
{
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(GridView1.DataKeys[index].Value.ToString()));
int tweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
LikeHelper.Like(tweetID, userId);
}
else
LikeHelper.Like(int.Parse(GridView1.DataKeys[index].Value.ToString()), userId);
}
if (e.CommandName == "ReTweet")
{
int index = Convert.ToInt32(e.CommandArgument);
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(GridView1.DataKeys[index].Value.ToString())))
{
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(GridView1.DataKeys[index].Value.ToString()));
int tweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
ReTweetHelper.ReTweet(tweetID, userId);
}
else
ReTweetHelper.ReTweet(int.Parse(GridView1.DataKeys[index].Value.ToString()), userId);
}
if (e.CommandName == "UnReTweet")
{
int index = Convert.ToInt32(e.CommandArgument);
int RetweetID = ReTweetHelper.GetReTweetIdFromReTweetByUserIdAndTweetId(int.Parse(GridView1.DataKeys[index].Value.ToString()), userId);
int TweetID = NewTweetHelper.GetTweetIdFromTweetByReTweetId(RetweetID);
ReTweetHelper.RemoveReTweet(RetweetID);
NewTweetHelper.GeneralRemoveTweet(TweetID);
}
if (e.CommandName == "Redirect")
{
int index = Convert.ToInt32(e.CommandArgument);
int TweetID = int.Parse(GridView1.DataKeys[index].Value.ToString());
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(TweetID))
{
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(TweetID);
int RealTweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
int UserID = NewTweetHelper.GetUserIdFromTweetByTweetId(RealTweetID);
Response.Redirect("ProfilePage.aspx?UserName=" + UserHelper.GetUserName(UserID));
}
else
Response.Redirect("ProfilePage.aspx?UserName=" + UserHelper.GetUserName(NewTweetHelper.GetUserIdFromTweetByTweetId(TweetID)));
}
}
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridView1.DataBind();
//TextBox TextBox = GridView1.Rows[e.NewEditIndex].FindControl("TweetTB") as TextBox;
//HiddenField TweetID = GridView1.Rows[e.NewEditIndex].FindControl("TweetID") as HiddenField;
//TextBox.Text = NewTweetHelper.GetTweetFromTweetByTweetId(int.Parse(TweetID.Value.ToString())).TweetText;
}
protected void GridView1_Cancel(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GridView1.DataBind();
}
public void BindGridview()
{
int userId = int.Parse(Session["UserID"].ToString());
ServiceReference1.WebServiceSoapClient objWs = new ServiceReference1.WebServiceSoapClient();
DataSet ds = objWs.SelectTweets(userId, 0);
DataTable dt = ds.Tables[0];
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int userId = int.Parse(Session["UserID"].ToString());
int index = Convert.ToInt32(e.RowIndex);
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(GridView1.DataKeys[index].Value.ToString())))
{
int RetweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(GridView1.DataKeys[index].Value.ToString()));
ReTweetHelper.RemoveReTweet(RetweetID);
NewTweetHelper.GeneralRemoveTweet(int.Parse(GridView1.DataKeys[index].Value.ToString()));
}
else
NewTweetHelper.GeneralRemoveTweet(Convert.ToInt32(GridView1.DataKeys[index].Value.ToString()));
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
int userId = int.Parse(Session["UserID"].ToString());
if (e.Row.RowType == DataControlRowType.DataRow)
{
HiddenField userIdLbl = (HiddenField)e.Row.FindControl("UserID");
HiddenField tweetid = (HiddenField)e.Row.FindControl("TweetID");
LinkButton editBt = (LinkButton)e.Row.FindControl("Edit");
editBt.Visible = userId == Convert.ToInt32(userIdLbl.Value);
ImageButton ProfileImage = e.Row.FindControl("ProfileImage") as ImageButton;
ProfileImage.ImageUrl = "~/UploadedImages/" + UserHelper.GetImageUrl(int.Parse(userIdLbl.Value.ToString()));
// if retweet
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString())))
{
Tweet tweet = NewTweetHelper.GetTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString()));
string FullName = UserHelper.GetName(tweet.UserID);
// change tweet
Label name = e.Row.FindControl("FullNameLabel") as Label;
Label UserName = e.Row.FindControl("UserNameLabel") as Label;
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(tweetid.Value.ToString()));
int RealTweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
int RealUserID = NewTweetHelper.GetUserIdFromTweetByTweetId(RealTweetID);
name.Text = "Retweeted by " + FullName + "<br>" + UserHelper.GetName(RealUserID);
UserName.Text = UserHelper.GetUserName(RealUserID);
ProfileImage.ImageUrl = "~/UploadedImages/" + UserHelper.GetImageUrl(RealUserID);
editBt.Visible = false;
}
//if there is image
Image img = (Image)e.Row.FindControl("TweetPic");
img.Visible = img.ImageUrl != "~/UploadedImages/";
//stats
Label LikeStat = e.Row.FindControl("LikeStat") as Label;
Label ReTweetStat = e.Row.FindControl("ReTweetStat") as Label;
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString())))
{
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(tweetid.Value.ToString()));
int RealTweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
LikeStat.Text = LikeHelper.AmountOfLikesByTweetId(RealTweetID).ToString();
if (int.Parse(LikeStat.Text.ToString()) > 0)
LikeStat.Visible = true;
ReTweetStat.Text = ReTweetHelper.AmountOfReTweets(RealTweetID).ToString();
if (int.Parse(ReTweetStat.Text.ToString()) > 0)
ReTweetStat.Visible = true;
}
else
{
LikeStat.Text = LikeHelper.AmountOfLikesByTweetId(int.Parse(tweetid.Value.ToString())).ToString();
if (int.Parse(LikeStat.Text.ToString()) > 0)
LikeStat.Visible = true;
ReTweetStat.Text = ReTweetHelper.AmountOfReTweets(int.Parse(tweetid.Value.ToString())).ToString();
if (int.Parse(ReTweetStat.Text.ToString()) > 0)
ReTweetStat.Visible = true;
}
// retweeted
if (ReTweetHelper.IsReTweetExistByUserIdAndTweetId(userId,int.Parse(tweetid.Value.ToString())))
{
ImageButton Retweet = e.Row.FindControl("ReTweetImgBTN") as ImageButton;
Retweet.ImageUrl = "~/SrcImage/retweet-action-on.png";
Retweet.CommandName = "UnReTweet";
}
if (NewTweetHelper.IsTweetByUser(int.Parse(tweetid.Value.ToString()), userId))
{
ImageButton Retweet = e.Row.FindControl("ReTweetImgBTN") as ImageButton;
Retweet.ImageUrl = "~/SrcImage/retweet-action-inactive.png";
Retweet.CommandName = null;
}
//Like Button
ImageButton LikeImg = e.Row.FindControl("LikeImgBTN") as ImageButton;
if (NewTweetHelper.IsTweetReTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString())))
{
int ReTweetID = NewTweetHelper.GetReTweetIDFromTweetByTweetID(int.Parse(tweetid.Value.ToString()));
int RealTweetID = ReTweetHelper.GetTweetIDFromReTweetByReTweetID(ReTweetID);
if(LikeHelper.IsUserLikeTweet(userId,RealTweetID))
LikeImg.ImageUrl = "~/SrcImage/like-action-on.png";
}
else
{
if (LikeHelper.IsUserLikeTweet(userId,int.Parse(tweetid.Value.ToString())))
LikeImg.ImageUrl = "~/SrcImage/like-action-on.png";
}
//Hyper Link Text
Label TweetLabel = (Label)e.Row.FindControl("TweetLabel");
//TextBox TweetTB = (TextBox)e.Row.FindControl("TweetTB");
Tweet TweetText = NewTweetHelper.GetTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString()));
//TweetTB.Text = "a";// TweetText.TweetText.ToString();
string text = NewTweetHelper.HyperLinkTweet(int.Parse(tweetid.Value.ToString()));
//TweetText.TweetText= text; //need?
TweetLabel.Text = text;
//Change Tb in edit cand do it in RowEditting
//if (e.Row.RowState == DataControlRowState.Edit)
//{
// TextBox TextBox = e.Row.FindControl("TweetTB") as TextBox;
// Tweet Text = NewTweetHelper.GetTweetFromTweetByTweetId(int.Parse(tweetid.Value.ToString()));
// TextBox.Text = "abc";
//}
}
}
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
HiddenField TweetID = GridView1.Rows[e.RowIndex].FindControl("TweetID") as HiddenField;
TextBox TweetText = GridView1.Rows[e.RowIndex].FindControl("TweetTB") as TextBox;
NewTweetHelper.UpdateTweet(int.Parse(TweetID.Value), TweetText.Text);
GridView1.EditIndex = -1;
BindGridview();
}
In the RowEditing event, you can set the EditIndex value and re-bind the data to the GridView:
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
BindGridView();
}
protected void GridView1_Cancel(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
BindGridView();
}
Then, in the RowDataBound event, you can access the controls of the row:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == GridView1.EditIndex)
{
TextBox txtBox = e.Row.FindControl("TweetTB") as TextBox;
...
}
else
{
...
}
}
How to get gridview row values when checkbox is checked. I am using this code in button's click event, but it's not working .
Html Code:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Width="100%"
DataKeyNames="ReportId" OnRowDataBound="GridView2_OnRowDataBound" ForeColor="#333333"
PageSize="5" Style="text-align: center">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxG1" runat="server" />
</ItemTemplate>
C# Code:
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox CheckRow = (row.Cells[0].FindControl("CheckBoxG1") as CheckBox);
if (CheckRow.Checked)
{
}
}
}
}
I can not see how you bound data and where is your button placement. So this is work sample.
<asp:Button Text="text" runat="server" OnClick="Unnamed_Click" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ReportId" Width="100%"
ForeColor="#333333" PageSize="5" Style="text-align: center">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBoxG1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
GridView1.DataSource = new RowModel[]
{
new RowModel { ReportId = "1" },
new RowModel { ReportId = "2" },
new RowModel { ReportId = "3" }
};
GridView1.DataBind();
}
}
protected void Unnamed_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
CheckBox CheckRow = (row.Cells[0].FindControl("CheckBoxG1") as CheckBox);
if (CheckRow.Checked)
{
}
}
}
}
public class RowModel
{
public string ReportId { get; set; }
}
In My sample code I have consider manually data while binding gridview because as you don't specify how you have bind your gridview through database or not, but it should work in both approaches.
My HTML code
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Get Checkbox Selected Row Values from Gridview in Asp.net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvDetails" DataKeyNames="UserId" AutoGenerateColumns="false" CellPadding="5" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="UserId" DataField="UserId" />
<asp:BoundField HeaderText="UserName" DataField="UserName" />
<asp:BoundField HeaderText="Education" DataField="Education" />
<asp:BoundField HeaderText="Location" DataField="Location" />
</Columns>
<HeaderStyle BackColor="#df5015" Font-Bold="true" ForeColor="White" />
</asp:GridView>
<asp:Button ID="btnProcess" Text="Get Selected Records" runat="server" Font-Bold="true" onclick="btnProcess_Click" />
<br />
<asp:Label ID="lblmsg" runat="server" />
</div>
</form>
</body>
</html>
Code Behind: This is just for binding GridView with proper data
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridviewData();
}
}
protected void BindGridviewData()
{
DataTable dt = new DataTable();
dt.Columns.Add("UserId", typeof(Int32));
dt.Columns.Add("UserName", typeof(string));
dt.Columns.Add("Education", typeof(string));
dt.Columns.Add("Location", typeof(string));
DataRow dtrow = dt.NewRow(); //Create New Row
dtrow["UserId"] = 1; //Bind Data to Columns
dtrow["UserName"] = "SureshDasari";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Chennai";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); //Create New Row
dtrow["UserId"] = 2; //Bind Data to Columns
dtrow["UserName"] = "MadhavSai";
dtrow["Education"] = "MBA";
dtrow["Location"] = "Nagpur";
dt.Rows.Add(dtrow);
dtrow = dt.NewRow(); //Create New Row
dtrow["UserId"] = 3; //Bind Data to Columns
dtrow["UserName"] = "MaheshDasari";
dtrow["Education"] = "B.Tech";
dtrow["Location"] = "Nuzividu";
dt.Rows.Add(dtrow);
gvDetails.DataSource = dt;
gvDetails.DataBind();
}
Code of Button_Click event
protected void btnProcess_Click(object sender, EventArgs e)
{
string str = string.Empty;
string strname = string.Empty;
string edu = string.Empty;
string location = string.Empty;
foreach (GridViewRow gvrow in gvDetails.Rows)
{
CheckBox chk = (CheckBox)gvrow.FindControl("chkSelect");
if (chk != null & chk.Checked)
{
//To Fetch the row index
//str += gvDetails.SelectedIndex.ToString();
//To Fetch the value of Selected Row.
str += gvDetails.DataKeys[gvrow.RowIndex].Value.ToString() + ',';
strname += gvrow.Cells[2].Text + ',';
edu += gvrow.Cells[3].Text + ',';
location += gvrow.Cells[4].Text + ',';
}
}
str = str.Trim(",".ToCharArray());
strname = strname.Trim(",".ToCharArray());
lblmsg.Text = "Selected UserIds: <b>" + str + "</b><br/>" + "Selected UserNames: <b>" + strname + "</b><br>" + " Education: <b>" + edu + "</b><br>" + " Location: <b>" + location + "</b><br>";
}
protected void Button1_Click(object sender, EventArgs e)
{
int count= 0;
foreach (GridViewRow gvindex in GridView1.Rows)
{
CheckBox chck = gvrow.FindControl("CheckBoxG1") as CheckBox;
if (chck.Checked)
{
GridView1.EditIndex = count;
DataBind(); //Your Databind Function
}
count++;
}
I am binding a grid with DataTable, there are two columns which I am using, and the result in GridView1 is is,
HostelName | HostelCode
Alpha | 1
Bravo | 2
Charlie | 3
Now I want this HostelCode as a LinkButton for all the records which are in database, so that I can do further actions while clicking LinkButton.
Any help ??
I am using this code, but its not working,
for (int i = 0; i < dt.Rows.Count; i++)
{
LinkButton lb = new LinkButton();
lb = (LinkButton)GridView1.SelectedRow.FindControl("lbtnSelect");
lb.Text = dt.Rows[1].ToString();
}
lbtnSelect is the ID of my linkbutton.
You can use link button in template field of gridview and Eval function to bind value in linkbutton in aspx page.
<asp:GridView runat="server" ID="gvrecords" CssClass="Gridview" DataKeyNames="HostelCode"
AutoGenerateColumns="false" HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="White"
OnRowDataBound="gvrecords_RowDataBound">
<Columns>
<asp:BoundField DataField="HostelName" HeaderText="Hostel Name" />
<asp:TemplateField HeaderText="Hostel Code">
<ItemTemplate>
<asp:LinkButton ID="lnkbtn" runat="server" OnClick="lnkbtn_Click" Text='<%#Eval("HostelCode")'></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
ASPX CODE
<asp:GridView runat="server" ID="gvrecords" CssClass="Gridview" DataKeyNames="HostelCode"
AutoGenerateColumns="false" HeaderStyle-BackColor="#7779AF" HeaderStyle-ForeColor="White"
OnRowDataBound="gvrecords_RowDataBound">
<Columns>
<asp:BoundField DataField="HostelName" HeaderText="Hostel Name" />
<asp:TemplateField HeaderText="Hostel Code">
<ItemTemplate>
<asp:LinkButton ID="lnkbtn" runat="server" OnClick="lnkbtn_Click"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CS CODE
public partial class Tests : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindHostelDetails();
}
}
protected void BindHostelDetails()
{
gvrecords.DataSource = DBData();
gvrecords.DataBind();
}
protected void gvrecords_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
string HostelCode = Convert.ToString(DataBinder.Eval(e.Row.DataItem, "HostelCode"));
LinkButton lnkbtnresult = (LinkButton)e.Row.FindControl("lnkbtn");
lnkbtnresult.Text = HostelCode;
}
}
protected void lnkbtn_Click(object sender, EventArgs e)
{
LinkButton lnkbtn = sender as LinkButton;
GridViewRow gvrow = lnkbtn.NamingContainer as GridViewRow;
int hostelcode = Convert.ToInt32(gvrecords.DataKeys[gvrow.RowIndex].Value.ToString());
string HostelName = gvrow.Cells[0].Text;
Response.Write("<script> alert('" + "Hostel Name :"+ HostelName +" Hostel Code :"+ hostelcode + "'); </script>");
}
List<DTest> DBData()
{
List<DTest> _Dt = new List<DTest>();
_Dt.Add(new DTest { HostelName = "Alpha", HostelCode = "1" });
_Dt.Add(new DTest { HostelName = "Bravo", HostelCode = "2" });
_Dt.Add(new DTest { HostelName = "Charlie", HostelCode = "3" });
return _Dt;
}
}
public class DTest
{
public string HostelName { get; set; }
public string HostelCode { get; set; }
}
I'm trying to delete a row in a gridview (the data is not in the database yet), so it should be a simple delete row, if anybody can please point me in the right direction....
This is what I have done:
else if (e.CommandName == "DeletePart")
{
int index = Convert.ToInt32(e.CommandArgument); //#1 line
GridView1.DeleteRow(index); //#2 line
}
The error that I am receiving is : "Input string was not in a correct format." (this happens on #1 line)...
This is how the gridview looks like: (use a linkbutton to do the delete)
<asp:GridView ID="GridView1" runat="server" AllowPaging="True"
EmptyDataText="No parts has been added to the model, please add a part."
BorderColor="Black" BorderStyle="Solid" BorderWidth="2px"
CellPadding="3" onrowcommand="GridView1_RowCommand"
onrowediting="GridView1_RowEditing" onrowdeleting="GridView1_RowDeleting">
<Columns>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="EditButton" runat="server" CssClass="EditButton" CommandName="Edit" Text="Edit" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="">
<ItemTemplate>
<asp:LinkButton ID="DeleteButton" runat="server" CssClass="DeleteButton" CommandName="DeletePart" CommandArgument='<%# Container.DataItemIndex %>' Text="Delete" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#FFFFCC" BorderColor="Black" BorderStyle="Solid"
BorderWidth="2px" />
</asp:GridView>
Class of how the gridview populated and binded:
public int companyID = 0;
public int methodID = 0;
DataTable dt;
#region SQLConnections
string connectionString = ConfigurationManager.ConnectionStrings["SOSConnectionString"].ConnectionString;
SqlConnection conn;
#endregion
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
dt = new DataTable();
MakeDataTable();
EmptyDataString();
}
else
{
dt = (DataTable)ViewState["DataTable"];
}
ViewState["DataTable"] = dt;
}
#region GridView
private void EmptyDataString()
{
TemplateBuilder tmpEmptyDataTemplate = new TemplateBuilder();
tmpEmptyDataTemplate.AppendLiteralString("No parts has been added to the model, please add a part.");
GridView1.EmptyDataTemplate = tmpEmptyDataTemplate;
GridView1.DataBind();
}
private void MakeDataTable()
{
dt.Columns.Add("Item");
dt.Columns.Add("Quantity");
dt.Columns.Add("Price P/Quantity");
}
private void AddToDataTable()
{
DataRow dr = dt.NewRow();
dr["Item"] = txtPart.Text;
dr["Quantity"] = numQuantity.Text;
dr["Price P/Quantity"] = txtPricePQ.Text;
dt.Rows.Add(dr);
}
private void BindGrid()
{
GridView1.DataSource = dt;
GridView1.DataBind();
}
protected void btnAddPart_Click(object sender, EventArgs e)
{
AddToDataTable();
BindGrid();
ClearNewParts();
}
#endregion
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Edit")
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
txtPart.Text = row.Cells[2].Text;
numQuantity.Text = row.Cells[3].Text;
txtPricePQ.Text = row.Cells[4].Text;
}
}
else if (e.CommandName == "DeletePart")
{
//int iCount = GridView1.Rows.Count;
//for (int i = 1; i <= iCount; i++)
//{
// GridView1.DeleteRow(i);
//}
// int rowIndex = Convert.ToInt32(GridView1.SelectedRow);
int index = Convert.ToInt32(e.CommandArgument);
GridView1.DeleteRow(index);
//int index = Convert.ToInt32(e.CommandArgument);
//GridView1.DeleteRow(rowIndex);
}
GridView1.DataBind();
}
Found the solution, only needed to do a databound.... Here is the working code:
else if (e.CommandName == "Delete")
{
int index = Convert.ToInt32(e.CommandArgument);
GridView1.DeleteRow(index);
((DataTable)ViewState["DataTable"]).Rows[index].Delete();
((DataTable)ViewState["DataTable"]).AcceptChanges();
GridView1.DataSource = (DataTable)ViewState["Data"];
GridView1.DataBind();
}
Seems like you didn't mention CommandArgument property in the GridView.
<asp:GridView runat="server" ID="gv"
CommandName="DeletePart"
CommandArgument='<%# Container.DataItemIndex %>'>
</asp:GridView>
Add the CommandArgument as shown above.
Try this..
In ASPX:
<asp:GridView runat="server" ID="Gridview1" CommandName="delete" CommandArgument='<%#Container.DataItem.Index %>'/>
Cs:
else if (e.CommandName == "DeletePart")
{
int index = Convert.ToInt32(e.CommandArgument);
GridView1.DeleteRow(index);
}
try int.TryParse , this will solve the input string fromat problem , but why is it occuring that you need to check the CommandArgument you are setting.
else if (e.CommandName == "DeletePart")
{
int index =-1;
if(int.TryParse(e.CommandArgument,out index)) //#1 line
GridView1.DeleteRow(index); //#2 line
}
Thy This:)
<asp:GridView ID="GridView1" runat="server" CssClass="gridview"
HorizontalAlign="Left" PagerSettings-Visible="true" AllowPaging="True"
PageSize ="5" Width="300px" >
<Columns>
<asp:CommandField ShowDeleteButton="True" ButtonType="Button" />
</Columns>
</asp:GridView>
then code behinde:
Protected Sub GridView1_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles GridView1.RowDeleting
DirectCast(ViewState("CurrentDataReference"), DataTable).Rows.RemoveAt(e.RowIndex)
GridView1.DataSource = DirectCast(ViewState("CurrentDataReference"), DataTable)
GridView1.DataBind()
End Sub
This seems like a repeated question but i'm not able to get my answer.
I have a grid view and I need to delete a particular row, when I click on a button outside the gridview.
protected void btnDelete_Click(object sender, EventArgs e)
{
dtable = (DataTable)Session["data"];
DataRow row = dtable.Rows[DataGV1.SelectedIndex];
dtable.Rows.Remove(row);
DataGV1.DataSource = dtable;
DataGV1.DataBind();
Session["data"] = dtable;
}
The session variable has the previous state of datatable.
protected void DataGV1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView _gridView = (GridView)sender;
// Get the selected index
_selectedIndex = int.Parse(e.CommandArgument.ToString());
}
Gridview controls
onselectedindexchanged="DataGV1_SelectedIndexChanged"
OnRowCommand="DataGV1_RowCommand" OnRowDeleting="DataGV1_RowDeleting"
AutoGenerateSelectButton="False" DataKeyNames="Role,Last_name">
<Columns>
<asp:ButtonField DataTextField="last_name" HeaderText="Last_name" CommandName="SingleClick"
SortExpression="last_name" Text="Button" />
<asp:BoundField DataField="role" HeaderText="role" SortExpression="role" />
<asp:BoundField DataField="role" HeaderText="role" HeaderText="Frist_name"
SortExpression="first_name" Text="First_name" />
</Columns>
</asp:GridView>
This doesn't seem to work.
Can u please tell me where I am going wrong?
If button is outside the GridView then no need to handle RowCommand event (In fact it is inappropriate).
Suggestion:
You have to add a TemplateField column, drop the CheckBox control in ItemTemplate of TemplateField and write code in click handler of button to traverse the GridView.Rows collection, identify the selected row by reading value of CheckBox control and perform deletion action if that CheckBox is checked.
Demo DataSource (List<T>)
public class Item
{
public int ID { get; set; }
public string Name { get; set; }
public static List<Item> Data()
{
List<Item> list = new List<Item>()
{
new Item(){ ID=11, Name="A"},
new Item(){ ID=12, Name="B"},
new Item(){ ID=13, Name="C"},
new Item(){ ID=14, Name="D"},
new Item(){ ID=15, Name="E"},
};
return list;
}
}
Markup:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:ButtonField DataTextField="Name" HeaderText="Name" CommandName="SingleClick"
SortExpression="last_name" Text="Button" />
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
</Columns>
</asp:GridView>
<asp:Button ID="btnDelete" runat="server" Text="Button" />
Code-behind (Page_Load)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["data"] = Item.Data();
GridView1.DataSource = Session["data"];
GridView1.DataBind();
}
/*--- RowCommand handler ---*/
GridView1.RowCommand += (sa, ea) =>
{
ViewState["RowIndex"] = ea.CommandArgument.ToString();
};
/*--- Delete button click handler ---*/
btnDelete.Click += (sa, ea) =>
{
if (ViewState["RowIndex"] != null)
{
int index = int.Parse(ViewState["RowIndex"].ToString());
List<Item> items = Session["data"] as List<Item>;
items.RemoveAt(index);
GridView1.DataSource = Session["data"];
GridView1.DataBind();
ViewState["RowIndex"] = null;
}
};
}
You have to store the _selectedIndex in a ViewState, and then on delete button click you retrieve the _selectedIndex from the Viewstate and use that to delete the row from your dataset, and reload the grid.
protected void DataGV1_RowCommand(object sender, GridViewCommandEventArgs e)
{
GridView _gridView = (GridView)sender;
// Get the selected index
ViewState["SelIndex"] = e.CommandArgument.ToString();
}
protected void btnDelete_Click(object sender, EventArgs e)
{
if(ViewState["SelIndex"] == null)
return;
int selIndex = int.Parse(ViewState["SelIndex"]);
dtable = (DataTable)Session["data"];
DataRow row = dtable.Rows[selIndex ];
dtable.Rows.Remove(row);
DataGV1.DataSource = dtable;
DataGV1.DataBind();
Session["data"] = dtable;
}
take a look at these articles that would explain to delete a single/multiple rows from gridview.
http://technico.qnownow.com/2012/06/15/how-to-delete-multiple-rows-from-gridview-with-checkboxes/
http://technico.qnownow.com/2012/06/14/how-to-delete-a-row-from-gridview-with-client-side-confirmation/