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; }
}
Related
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>
I have a GridView called gridview1
What I want is that if the user select or click on specific row some action will happen.
For example I want to get the value from that row and store it in a new variable.
How can I do it? I'm confused about what I should do to get the value?
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
string stuId = ?
}
<asp:GridView ID="GridView1" runat="server" HeaderStyle-BackColor="#3AC0F2" HeaderStyle-ForeColor="White"
AutoGenerateColumns="false" OnSelectedIndexChanged = "OnSelectedIndexChanged">
<Columns>
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:TemplateField HeaderText="Country" ItemStyle-Width="150">
<ItemTemplate>
<asp:Label ID="lblCountry" runat="server" Text='<%# Eval("Country") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:ButtonField Text="Select" CommandName="Select" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<br />
<u>Selected Row Values: </u>
<br />
<br />
<asp:Label ID="lblValues" runat="server" Text=""></asp:Label>
aspx.cs code
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"), new DataColumn("Name"), new DataColumn("Country") });
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
GridView1.DataSource = dt;
GridView1.DataBind();
}
}
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
//Accessing BoundField Column
string name = GridView1.SelectedRow.Cells[0].Text;
//Accessing TemplateField Column controls
string country = (GridView1.SelectedRow.FindControl("lblCountry") as Label).Text;
lblValues.Text = "<b>Name:</b> " + name + " <b>Country:</b> " + country;
}
you simply copy and paste your issue is resolve.
you could use like this:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns = "false"
OnRowCommand = "OnRowCommand">
<Columns>
<asp:ButtonField CommandName = "ButtonField" DataTextField = "StudID"
ButtonType = "Button"/>
</Columns>
</asp:GridView>
protected void OnRowCommand(object sender, GridViewCommandEventArgs e)
{
int index = Convert.ToInt32(e.CommandArgument);
GridViewRow gvRow = GridView1.Rows[index];
}
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'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