How to read gridview column and row wise data in asp.net? - c#

I want to read the gridview column data in c#.
I am using C# as a backend and ASP.Net as backend.
front end: asp grid view
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" onrowcommand="GridView2_RowCommand" DataKeyNames="ID" >
<Columns>
<asp:BoundField DataField="NAME" HeaderText="EVENT NAME" />
<asp:BoundField DataField="TYPE" HeaderText="TYPE OF EVENT" />
<asp:BoundField DataField="desc" HeaderText="DESCRIPTI0ON OF EVENT" />
<asp:TemplateField HeaderText="Poster">
<EditItemTemplate>
<asp:FileUpload ID="FileUpload" runat="server" />
</EditItemTemplate>
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("poster") %>' Height="100px" Width="150px" />
</ItemTemplate>
</asp:TemplateField>
**<asp:TemplateField HeaderText="Team Name">
<EditItemTemplate>
<asp:TextBox ID="TextBox" runat="server" ></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:TextBox ID="TextBox" runat="server" ></asp:TextBox>
</ItemTemplate>**
<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>
<asp:ButtonField ButtonType="Button" Text="participate" CommandName="participate" HeaderText="participation" />
</Columns>
</asp:GridView>
c# protected void GridView2_RowCommand
protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
con = new SqlConnection(ConfigurationManager.ConnectionStrings["Event_ManagementConnectionString"].ConnectionString);
SqlCommand cmd;
int rowindex = Convert.ToInt32(e.CommandArgument);
GridViewRow SelectedRow = GridView2.Rows[rowindex];
string id = Convert.ToString(GridView2.DataKeys[rowindex].Values[0]);
string team_name = SelectedRow.Cells[4].Text;
//= Convert.ToString(GridView2.Rows[rowindex].Values[4]);
Response.Write(team_name+"what the hell it is"+ SelectedRow.Cells[0].Text+SelectedRow.Cells[1].Text+ SelectedRow.Cells[2].Text+ SelectedRow.Cells[3].**Text+ SelectedRow.Cells[4].Text**);
if (e.CommandName == "participate")
{
if (team_name == "null")
{
Label3.Text = "Team name cant be blank";
Label3.Visible = true;
}
}
}
}
How to get the team name from the gridview?
I am unable to get data from column 4: SelectedRow.Cells[4].Text;

Team name holds in a textbox control of column 4. so, select team text control and you should get team name as text property of text box. Change code like this:
int rowindex = Convert.ToInt32(e.CommandArgument);
GridViewRow SelectedRow = GridView2.Rows[rowindex];
string id = Convert.ToString(GridView2.DataKeys[rowindex].Values[0]);
TextBox txtteam= (TextBox)SelectedRow.Cells[4].FindControl("TextBox");
string team_name = txtteam.Text;
//= Convert.ToString(GridView2.Rows[rowindex].Values[4]);
Response.Write(team_name + "what the hell it is" + SelectedRow.Cells[0].Text + SelectedRow.Cells[1].Text + SelectedRow.Cells[2].Text + SelectedRow.Cells[3].Text + txtteam.Text);
if (e.CommandName == "participate")
{
if (team_name == "null")
{
Label3.Text = "Team name cant be blank";
Label3.Visible = true;
}
}

Related

How to get cell value in a GridView on LinkButton Click Event? Or RowCommand?

I Have a GridView which conntains multiple records and couple of Link Buttons Named Edit and Detail. Now i want to Get the Name of the User (NOT Index), when a user click on Detail Link Button. Like "Name", "FatherName" etc
Here is the .aspx code
<asp:GridView ID="dgvEmployeesInformation" runat="server" CssClass=" table table-bordered table-hover table-responsive" DataKeyNames="Id" AutoGenerateColumns="False" OnRowCommand="dgvEmployeesInformation_RowCommand" OnRowDataBound="dgvEmployeesInformation_RowDataBound" AllowPaging="True" AllowSorting="True" OnPageIndexChanging="dgvEmployeesInformation_PageIndexChanging">
<%--1st Column--%>
<Columns>
<asp:BoundField HeaderText="ID" DataField="Id" ControlStyle-BackColor="#0066ff" Visible="False">
<ControlStyle BackColor="#0066FF"></ControlStyle>
</asp:BoundField>
<asp:BoundField HeaderText="Name" DataField="Name" />
<asp:BoundField HeaderText="Employee No" DataField="EmployeeNo" />
<asp:BoundField HeaderText="Father Name" DataField="FatherName" />
<asp:HyperLinkField DataNavigateUrlFields="Id" DataNavigateUrlFormatString="AddEmployeeBasic1.aspx?thid={0}" HeaderText="Update" NavigateUrl="~/AddEmployeeBasic1.aspx" Text="Edit" />
<asp:TemplateField HeaderText="Action" ShowHeader="True">
<ItemTemplate>
<asp:LinkButton ID="lbDelete" runat="server" CausesValidation="False" CommandName="Delete" Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbDetail" OnClick="lbDetail_Click" DataNavigateUrlFields="Id" DataNavigateUrlFormatString="EmployeesDetails.aspx?EmpID={0}" NavigateUrl="~/EmployeesDetails.aspx" HeaderText="Show Detail" Text="Detail"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Here is the lbDetail_Click Code
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label lblUserName = (Label)clickedRow.FindControl("Name");
EmployeeID.EmpName = lblUserName.ToString();
}
When i put my program on Debugging mode, the lblUserName return NULL
Here is the picture.
What i want is that, when a user click on Detail LinkButton, then on lbDetail Click event, it gets the Name of the Employee and store it in a static variable. Following is the picture
I don't understand how to solve this problem. Please help me through this. Your help will be really appreciated.
I would just add data attributes to the details button then get it's values at code behind.
For example:
1.) Add new data-myData='<%# Eval("Name") %>' attribute and its value to button
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton runat="server" ID="lbDetail" OnClick="lbDetail_Click" Text="Detail" data-ID='<%# Eval("ID") %>' data-myData='<%# Eval("Name") %>' ></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
2.) Get those data from event handler
protected void lbDetail_Click(object sender, EventArgs e)
{
LinkButton button = (LinkButton)sender;
var name = (string)button.Attributes["data-myData"];
var selectedID = (string)button.Attributes["data-ID"];
Session["selectedID"] = selectedID ;
}
lblUserName is null because it's not a Label, but a BoundField.
What you could do it get the Cell value.
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
Label1.Text = clickedRow.Cells[1].Text;
}
Or use a TemplateField that does contain a Label Name
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<asp:Label ID="Name" runat="server" Text='<%# Eval("Name")%>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Here is how your code should look:
protected void lbDetail_Click(object sender, EventArgs e)
{
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
var username = clickedRow.Cells[1].Text;
if(string.IsNullOrEmpty(username))
{
return;
}
EmployeeID.EmpName = username;
}

System.ArgumentOutOfRangeException occurs while updating the datatable from the gridview

I'm updating the row in a grid view as well as the DataTable using the Rowcommand event but an exception occurs while assigning the values to the row in the DataTable.
protected void grduser_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
DataTable dt = (DataTable)ViewState["dtable"];
Int32 index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = grduser.Rows[index];
// after this statement the exception occurs!
dt.Rows[row.DataItemIndex]["userid"] = ((TextBox)(row.Cells[0].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["username"] = ((TextBox)(row.Cells[1].FindControl("txtuname"))).Text;
dt.Rows[row.DataItemIndex]["usertype"] = ((TextBox)(row.Cells[2].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["email"] = ((TextBox)(row.Cells[3].Controls[0])).Text;
dt.Rows[row.DataItemIndex]["salary"] = ((TextBox)(row.Cells[4].FindControl("txtsalary"))).Text;
grduser.EditIndex = -1;
ViewState["dtable"]=dt;
grduser.DataSource = (DataTable)(ViewState["dtable"]);
grduser.DataBind();
}
}
// The grid view source below.
<asp:GridView ID="grduser" runat="server" AutoGenerateColumns="False"
onrowediting="grduser_RowEditing" onrowupdating="grduser_updateRow"
>
<Columns>
<asp:BoundField HeaderText="Id" DataField="userid"/>
<asp:TemplateField HeaderText="Name">
<EditItemTemplate>
<asp:TextBox ID="txtuname" runat="server" Text='<%# Bind("username") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("username") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="User Type" DataField="usertype" />
<asp:BoundField HeaderText="Email" DataField="email" />
<asp:TemplateField HeaderText="Salary">
<EditItemTemplate>
<asp:TextBox ID="txtsalary" runat="server" Text='<%# Bind("salary") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("salary") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Could you try this.
protected void grduser_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Update")
{
DataTable dt = (DataTable)ViewState["dtable"];
Int32 index = Convert.ToInt32(e.CommandArgument);
GridViewRow row = grduser.Rows[index];
dt.Rows[row.DataItemIndex]["userid"] = row.Cells[0].Text;
dt.Rows[row.DataItemIndex]["username"] = ((TextBox)(row.FindControl("txtuname"))).Text;
dt.Rows[row.DataItemIndex]["usertype"] = row.Cells[2].Text;
dt.Rows[row.DataItemIndex]["email"] = row.Cells[3].Text;
dt.Rows[row.DataItemIndex]["salary"] = ((TextBox)(row.FindControl("txtsalary"))).Text;
grduser.EditIndex = -1;
ViewState["dtable"]=dt;
grduser.DataSource = (DataTable)(ViewState["dtable"]);
grduser.DataBind();
}
}
You are getting that error because your e.CommandArgument is not a valid row number from your GridView. For instance, your grduser has 3 rows and your e.CommandArgument is set to 3. This will throw a System.ArgumentOutOfRangeException because the grduser.Rows is 0-based and you are most likely setting it starting with 1.

How to make this row in GridView in a Grey color when the Checkbox is unchecked?

I have the following database design:
Employee Table: Username, Name, JobTitle, BadgeNo, IsActive, DivisionCode
Divisions Table: SapCode, DivisionShortcut
And I have a GridView that I am using it to add, delete and update/edit the employees information. This information is employee Username, Name, BadgeNo, JobTitle, IsActive and the DivisionShortcut. IsActive is a flag that indicates if the employee is available or in an assignment. I made it as a checkbox and the column should show two values; Active and Inactive. In the Edit mode, the Checkbox will be displayed. If it is checked, then it means the employee is avaiable, otherwise it is inactive.
I wrote the code and everything works fine, but now I am facing only one problem which is the following: when the checkbox is unchecked that means the employee is inactive, so I want the row that shows his information to be in a grey color (like disabled).
So how to do that?
ASP.NET code:
<%-- GridView for User Management Subsystem --%>
<asp:GridView ID="GridView1" runat="server" AllowSorting="True"
AutoGenerateColumns="False" DataKeyNames="Username"
DataSourceID="SqlDataSource1" OnRowDataBound="GridView1_RowDataBound" BorderWidth="1px" BackColor="#DEBA84"
CellPadding="3" CellSpacing="2" BorderStyle="None"
BorderColor="#DEBA84">
<FooterStyle ForeColor="#8C4510"
BackColor="#F7DFB5"></FooterStyle>
<PagerStyle ForeColor="#8C4510"
HorizontalAlign="Center"></PagerStyle>
<HeaderStyle ForeColor="White" Font-Bold="True"
BackColor="#A55129"></HeaderStyle>
<Columns>
<asp:CommandField ButtonType="Image" ShowEditButton="true" ShowCancelButton="true"
EditImageUrl="Images/icons/edit24.png" UpdateImageUrl="Images/icons/update24.png"
CancelImageUrl="Images/icons/cancel324.png" />
<asp:TemplateField HeaderText="Division">
<ItemTemplate>
<%# Eval("DivisionShortcut")%>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="DivisionsList" runat="server" DataSourceID="DivisionsListDataSource"
DataTextField="DivisionShortcut" DataValueField="SapCode"
SelectedValue='<%# Bind("DivisionCode")%>'>
</asp:DropDownList>
</EditItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Username" HeaderText="Network ID" ReadOnly="True"
SortExpression="Username" />
<asp:TemplateField HeaderText="Name">
<ItemTemplate>
<%# Eval("Name")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtEmployeeName" runat="server" Text='<%# Bind("Name")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Job Title">
<ItemTemplate>
<%# Eval("JobTitle")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtJobTitle" runat="server" Text='<%# Bind("JobTitle")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Badge No.">
<ItemTemplate>
<%# Eval("BadgeNo")%>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txtBadgeNo" runat="server" Text='<%# Bind("BadgeNo")%>' />
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Is Active?">
<ItemTemplate>
<asp:Label ID="lblIsActive" runat="server" Text='<%# Eval("IsActive")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:CheckBox ID="isActive" runat="server"
AutoPostBack="true" OnCheckedChanged="isActive_OnCheckedChanged"
Checked='<%# Convert.ToBoolean(Eval("IsActive")) %>'
Text='<%# Eval("IsActive")%>'/>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete?">
<ItemTemplate>
<span onclick="return confirm('Are you sure to Delete the record?')">
<asp:ImageButton ID="lnkB" runat="server" ImageUrl="Images/icons/delete24.png" CommandName="Delete" />
</span>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Code-behind:
//for updating the (IsActive) column using checkbox inside the GridView
protected void isActive_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chkStatus = (CheckBox)sender;
GridViewRow gvrow = (GridViewRow)chkStatus.NamingContainer;
//Get the ID which is the NetworkID of the employee
string username = gvrow.Cells[2].Text;
bool status = chkStatus.Checked;
string connString = ConfigurationManager.ConnectionStrings["UsersInfoDBConnectionString"].ConnectionString;
SqlConnection conn = new SqlConnection(connString);
string updateIsActive = "UPDATE Employee SET IsActive = #IsActive WHERE Username = #Username";
SqlCommand cmd = new SqlCommand(updateIsActive, conn);
cmd.Parameters.AddWithValue("#IsActive", status);
cmd.Parameters.AddWithValue("#Username", username);
try
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
catch (SqlException se)
{
throw se;
}
finally
{
cmd.Dispose();
conn.Close();
conn.Dispose();
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
// First check Checkedbox is check or not, In Cells insert you IsActive column index
if( e.Row.Cells[1].Text == "False" )
GridView1.BackColor = Color.Gray;
}
}
in your method on unchecked status of the checkbox you will have set the BackColor of the GrdiViewRow like this gvrow.BackColor= Color.Gray;
One important think is on the first load you will need to repeat similar logic of the GridView's OnRowDataBound so move it in method and reuse
protected void isActive_OnCheckedChanged(object sender, EventArgs e)
{
CheckBox chkStatus = (CheckBox)sender;
GridViewRow gvrow = (GridViewRow)chkStatus.NamingContainer;
//Get the ID which is the NetworkID of the employee
string username = gvrow.Cells[2].Text;
bool status = chkStatus.Checked;
if(!status)//this is checkbox is unchecked then set backcolor to Gray
{
gvrow .BackColor = Color.Gray;
}
.......

update Ajax rating control, update comments

I am trying to update the value of ajaxrating control and comments in the database`
` <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="id"
onrowdatabound="GridView1_RowDataBound" >
<Columns>
<asp:BoundField HeaderText="PurchasedPID" DataField="PurchasedPID"/>
<asp:BoundField HeaderText="DatetimePurchased" DataField="orderdate" />
<asp:BoundField HeaderText="MMBName" DataField="MMBName" />
<asp:TemplateField HeaderText="Rating">
<ItemTemplate>
<asp:Rating RatingDirection="LeftToRightTopToBottom" Visible="true" AutoPostBack="true"
ID="Rating2" runat="server" MaxRating="5"
StarCssClass="star_rating" EmptyStarCssClass="star_empty"
FilledStarCssClass="star_filled" WaitingStarCssClass="star_saved" CurrentRating='<%# Bind("Rating") %>'
OnChanged="Rating2_Changed" >
</asp:Rating>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Comments">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text= '<%# Bind("Comments") %>' multiline="true">
</asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server">Submit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
So I added the following rowcommand event on of the members suggestion.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Submit")
{
GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
Int32 Id = Convert.ToInt32(e.CommandArgument);
int ratingScore = ((AjaxControlToolkit.Rating)row.FindControl("Rating2")).CurrentRating;
TextBox TextComments = row.FindControl("TextBox1") as TextBox;
string comments = TextComments.Text;
objBLL.UpdateRating(ratingScore, Id,comments);
}
But here instead of getting the new rating, it is inserting the CurrentRating in the table.
int ratingScore = ((AjaxControlToolkit.Rating)row.FindControl("Rating2")).CurrentRating;
I think its because of this CurrentRating here.
Any idea how to get the value of updated rating? Or should i use an additional Rating_changed event to update the rate, and then a row command event to update the comments
Thanks
Sun
The easiest way to bind the your DataKey/ItemID to the Tag attribute of the Rating control
<asp:Rating RatingDirection="LeftToRightTopToBottom" Visible="true"
AutoPostBack="true"
ID="Rating2" runat="server" MaxRating="5" **Tag='<%# Bind("id")%>'**
StarCssClass="star_rating" EmptyStarCssClass="star_empty"
FilledStarCssClass="star_filled" WaitingStarCssClass="star_saved"
CurrentRating='<%# Bind("Rating") %>'
OnChanged="Rating2_Changed" >
</asp:Rating>
Event Handler
protected void Rating2_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
{
Rating r = sender as Rating;
int id = Convert.ToInt32(r.Tag);
objBLL.UpdateRating(Convert.ToInt32(e.Value),id)
}
You can use GridView1_RowCommand to update rating score in the DB. e.g.
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Rating")
{
GridViewRow row = (GridViewRow)(((ImageButton)e.CommandSource).NamingContainer);
Int32 Id = Convert.ToInt32(e.CommandArgument);
ratingScore = ((AjaxControlToolkit.Rating)row.FindControl("Rating2")).CurrentRating;
}
}
Set CommandName="Rating" to your linkbutton
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:LinkButton ID="LinkButton1" runat="server" CommandName="Rating">Submit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>

Linkbutton inside a gridview not firing

<asp:GridView ID="gvBlockUnblock" runat="server" AutoGenerateColumns="False"
BackColor ="AliceBlue"
onrowdatabound="gvBlockUnblock_RowDataBound" DataKeyNames="CPID,PUBLISHED"
style="margin-top: 0px"
AllowPaging="True" onpageindexchanging="gvBlockUnblock_PageIndexChanging"
PageSize="10" EnableViewState= "true"
onselectedindexchanged="gvBlockUnblock_SelectedIndexChanged" >
<Columns>
<asp:TemplateField HeaderText="S.No.">
<ItemTemplate>
<asp:LinkButton ID="lbSNo" runat="server"
Text='<%# (Eval("sno")) %>'
PostBackUrl='<%#"~/_UILayer/ComplaintReport.aspx?PINo="+Eval("CPID") %>' >
</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText = "Complaint" />
<asp:HyperLinkField DataNavigateUrlFields="CPID" datatextfield = "CPID"
DataNavigateUrlFormatString="WebForm1.aspx?CPID={0}" HeaderText=" Problem Item No"/>
<asp:BoundField DataField="NewComplaints"
HeaderText="Number of New Complaints" SortExpression="NewComplaints" />
<asp:BoundField DataField="TotalNumberofComplaints"
HeaderText="Total Number of Complaints" SortExpression="TotalNumberofComplaints" />
<asp:BoundField DataField="NumberofUnblocks" HeaderText="Number of Unblocks"
SortExpression="TotalNumberofComplaints" />
<asp:TemplateField HeaderText = "Comments">
<ItemTemplate>
<asp:TextBox ID="txtAdminComment" Font-Names="Arial" ReadOnly="false" Width="200" Height="30"
TextMode="multiLine" runat="server" BorderStyle="NotSet"></asp:TextBox>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText = " Block / Unblock">
<ItemTemplate>
<asp:button ID ="btnBlockUnblock" runat = "server"
Text = '<%# CheckBlock(Eval("PUBLISHED")) %>' CommandName="Select"
CommandArgument="<%# ((GridViewRow) Container).RowIndex %>" CausesValidation="False" />
</ItemTemplate>
</asp:TemplateField>
<asp:HyperLinkField DataNavigateUrlFields="CPID" Text="View Details"
DataNavigateUrlFormatString="ItemHistoryForm.aspx?CPID={0}" HeaderText=" Problem Item No"/>
</Columns>
</asp:GridView>
aspx.cs
protected void gvBlockUnblock_SelectedIndexChanged(object sender, EventArgs e)
{
string ComplaintProfileId = gvBlockUnblock.DataKeys[gvBlockUnblock.SelectedIndex].Values["CPID"].ToString();
string ISPUBLISHED = gvBlockUnblock.DataKeys[gvBlockUnblock.SelectedIndex].Values["PUBLISHED"].ToString();
string date = System.DateTime.Now.ToString();
TextBox tb = (TextBox)gvBlockUnblock.Rows[gvBlockUnblock.SelectedIndex].FindControl("txtAdminComment");
string Comment = tb.Text;
if (string.IsNullOrEmpty(Comment))
{
WebMsgBox.Show("empty");
}
else
{
if (ISPUBLISHED == "N")
{
ISPUBLISHED = "N";
}
else
{
ISPUBLISHED = "Y";
}
string AdminComment = (System.DateTime.Now.ToString() + " : " + Comment);
AddCommentBLL.InsertComment(AdminComment, ComplaintProfileId, ISPUBLISHED);
gvBlockUnblock.DataSource = AddCommentBLL.GetItem();
gvBlockUnblock.DataBind();
}
}
So, on click of the button ID ="btnBlockUnblock", this grid view selectedindex changed needs to fire. The page is refreshing though.
Thanks
Sun
You have to use the GridView RowCommand event instead of the GridView SelectedIndex Change.. e.g
protected void gvBlockUnblock_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Select")
{
string ComplaintProfileId = gvBlockUnblock.DataKeys[gvBlockUnblock.SelectedIndex].Values["CPID"].ToString();
string ISPUBLISHED = gvBlockUnblock.DataKeys[gvBlockUnblock.SelectedIndex].Values["PUBLISHED"].ToString();
string date = System.DateTime.Now.ToString();
TextBox tb = (TextBox)gvBlockUnblock.Rows[gvBlockUnblock.SelectedIndex].FindControl("txtAdminComment");
string Comment = tb.Text;
if (string.IsNullOrEmpty(Comment))
{
WebMsgBox.Show("empty");
}
else
{
if (ISPUBLISHED == "N")
{
ISPUBLISHED = "N";
}
else
{
ISPUBLISHED = "Y";
}
string AdminComment = (System.DateTime.Now.ToString() + " : " + Comment);
AddCommentBLL.InsertComment(AdminComment, ComplaintProfileId, ISPUBLISHED);
gvBlockUnblock.DataSource = AddCommentBLL.GetItem();
gvBlockUnblock.DataBind();
}
}
}
Edit: After reading code from your comment, I found your problem.
What happens actually, when you click the button, the Page Load event fires before your gridview event and there your gridview data again binded and it lost your fired event. You have to examine your page Postback by putting if(!IsPostBack) in your page load where you are trying to bind your data to gridview.
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// gets the items table using stored proc GetItem
gvBlockUnblock.DataSource = AddCommentBLL.GetItem();
gvBlockUnblock.DataBind();
// used for paging
Session["MyDataSett"] = gvBlockUnblock.DataSource;
}
}

Categories

Resources