Linkbutton inside a gridview not firing - c#

<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;
}
}

Related

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

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;
}
}

GridView does not update values on postback?

I have a gridview with some custom templates:
<asp:GridView ID="gvGroups" runat="server" AutoGenerateColumns="False"
CssClass="table table-hover table-striped" GridLines="None" >
<Columns>
<asp:BoundField DataField="GroupDescription" HeaderText="Name" ReadOnly="True"
SortExpression="GroupDescription" />
<asp:TemplateField HeaderText="Administrator">
<ItemTemplate>
<asp:CheckBox ID="cbAdmin" runat="server"
Checked='<%# Boolean.Parse((Boolean)Eval("IsReadOnly") ? "True" : "False") ? false : true %>'/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Remove">
<ItemTemplate>
<asp:CheckBox ID="cbRemove" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="ID" SortExpression="GroupID" Visible="False">
<ItemTemplate>
<asp:Label ID="lblID" runat="server" Text='<%# Bind("GroupID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
I then have a button that I click and that is supposed to change group administration and remove groups that are checked.
Here is the button code:
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow gvr in gvGroups.Rows)
{
CheckBox cbAdmin = (CheckBox)gvr.FindControl("cbAdmin");
CheckBox cbRemove = (CheckBox)gvr.FindControl("cbRemove");
Label lblID = (Label)gvr.FindControl("lblID");
int id;
bool idValid = int.TryParse(lblID.Text,out id);
bool isReadOnly = !cbAdmin.Checked;
if (idValid)
{
Group g = SecurityManager.GetGroup(id);
if (g.IsReadOnly != isReadOnly)
{
bool updateSuccess = SecurityManager.ChangeGroupPermissions(id, isReadOnly);
}
if (cbRemove.Checked)
{
bool removeEmpSuccess = SecurityManager.RemoveEmployeesFromGroup(id);
bool removeSuccess = SecurityManager.RemoveGroup(id);
}
}
}
}
I used the debugger and even when I uncheck admin on all groups, when I look at cbAdmin.Checked, it is still true, which is the same value it started with, thus nothing ever happens.
What could be the problem? Why am I not seeing the updated values on the button postback?
Thanks
You have to call GridView#DataBind() within if(!IsPostBack){ }
Also you need to set AutoPostBack property of the textboxes to "true"
I guess that you're databinding the GridView on postbacks. That will load the data from database again and prevent changes. So ue the PostBack property of the Page:
protected void Page_Load(Object sender, EventArgs e)
{
if(!IsPostBack)
{
DataBindGridView();
}
}

GridView into UpdatePanel fires OnRowUpdating event : but I can see only the controls inside ItemTemplate instead of EditItemTemplate?

As i was written in the title, the problem is very funny :
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id_Newsletter" HeaderStyle-BackColor="Black"
HeaderStyle-ForeColor="White" RowStyle-BackColor="DarkGray" AlternatingRowStyle-BackColor="LightGray" PageSize="6" AllowPaging="true"
AllowSorting="true" ShowHeaderWhenEmpty="true" EmptyDataText="La tabella non contiene dati" EnableViewState="true" RowStyle-Wrap="true"
PagerStyle-HorizontalAlign="Left" PagerStyle-BorderWidth="0" BorderWidth="0" OnRowCommand="GridView_RowCommand"
OnRowCancelingEdit="GridView_RowCancelingEdit" OnRowUpdating="GridView_RowUpdating" OnRowDeleting="GridView_RowDeleting"
OnPageIndexChanging="GridView_PageIndexChanging" OnSorting="GridView_Sorting" OnRowEditing="GridView_RowEditing" CssClass="NewsletterManager_GridView" >
<Columns>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Indirizzo Email" HeaderStyle-Width="275" SortExpression="emailNewsletter">
<ItemTemplate>
<asp:Label ID="lbl_emailNewsletter" runat="server" Text='<%# Eval("emailNewsletter") %>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:Label ID="lbl_emailNewsletter" runat="server" Text='<%# Eval("emailNewsletter") %>' Visible="false" ></asp:Label>
<asp:TextBox ID="txt_emailNewsletter" runat="server" Text='<%# Bind("emailNewsletter") %>'></asp:TextBox>
</EditItemTemplate>
</asp:TemplateField>
<asp:TemplateField ItemStyle-HorizontalAlign="Center" HeaderText="Azioni" HeaderStyle-Width="100">
<EditItemTemplate>
<asp:ImageButton ID="Img_Aggiorna" runat="server" CommandName="Update" ImageUrl="~/images/GridIcon/update.png" ToolTip="Aggiorna" />
<asp:ImageButton ID="Img_Annulla" runat="server" CommandName="Cancel" ImageUrl="~/images/GridIcon/undo.png" ToolTip="Annulla" />
</EditItemTemplate>
<ItemTemplate>
<asp:ImageButton ID="Img_Modifica" runat="server" CommandName="Edit" ImageUrl="~/images/GridIcon/edit.png" ToolTip="Modifica" />
<asp:ImageButton ID="Img_Cancella" runat="server" CommandName="Delete" ImageUrl="~/images/GridIcon/delete.png" OnClientClick="return confirm('Sei sicuro di voler cancellare l\'email?');" ToolTip="cancella" />
</ItemTemplate>
</asp:TemplateField>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
LoadGridView(GridView1, -1, 0);
lbl_result.Text = String.Empty;
}
protected void GridView_RowEditing(Object sender, GridViewEditEventArgs e)
{
LoadGridView(((GridView)sender), e.NewEditIndex, ((GridView)sender).PageIndex);
}
protected void GridView_RowUpdating(Object sender, GridViewUpdateEventArgs e)
{
NewsLetterBL newsBl = new NewsLetterBL();
String oldmail = ((Label)((GridView)sender).Rows[e.RowIndex].FindControl("lbl_emailNewsletter")).Text;
String newmail = ((TextBox)((GridView)sender).Rows[e.RowIndex].FindControl("txt_emailNewsletter")).Text;
if (newsBl.ModifyWrongEmail(oldmail, newmail))
lbl_result.Text = "Modify Done";
else lbl_result.Text = newsBl.LastMessage;
LoadGridView(((GridView)sender), -1, ((GridView)sender).PageIndex);
}
protected void LoadGridView(GridView GV, int EditIndex, int PageIndex)
{
NewsLetterBL newsBl = new NewsLetterBL();
DataView dw = new DataView(newsBl.getFullNewsletter());
String SortExpression = GV.ID.ToString() + "_SortExpression";
if (ViewState[SortExpression] != null) dw.Sort = (String)ViewState[SortExpression];
GV.DataSource = dw;
GV.PageIndex = PageIndex;
GV.EditIndex = EditIndex;
GV.DataBind();
}
When I try to access to the txt_emailNewsletter control into the row in edit mode from the GridView_RowUpdating that handle the OnRowUpdating event of the GridView1, the element throws a NullReferenceException, but the lbl_emailNewsletter control can be founded.
The labels into ItemTemplate and EditItemTemplate have the same ID (lbl_emailNewsletter): if I change the ID of the label into the ItemTemplate, both the String oldmail and newmail throws an exception of null Reference ; clearly the problem is that when I click on ImageButton Img_Aggiorna with CommandName="Update", ASP.NET for a mysterious reason Find only controls of ItemTemplate instead of EditItemTemplate from the edited row.
GridView event "OnRowUpdating" is useful only if you use a datasource : in this case is possible to access to the Dictionary e.OldValues[] or e.NewValues[] and get correctly the old and new values.
I have solved the problem using the event "OnRowCommand" with a personalized CommandName and a CommandArgument with the old values : in this case is possible to access to all the controls inside the edited row in the GridView with the new values.
<asp:ImageButton ID="Img_Update" runat="server" CommandName="Change" CommandArgument='<%# Eval("emailNewsletter") %>' ImageUrl="~/images/GridIcon/update.png" ToolTip="Update" />
protected void GridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
switch (e.CommandName)
{
case "Change":
ImageButton btnNew = e.CommandSource as ImageButton;
GridViewRow row = btnNew.NamingContainer as GridViewRow;
TextBox txt_emailNewsletter = row.FindControl("txt_emailNewsletter") as TextBox;
if ( !CheckEmail(e.CommandArgument.ToString()) || !CheckEmail(txt_emailNewsletter.Text) )
lbl_result.Text = "ERROR : Email not Valid";
else {
if (txt_emailNewsletter.Text.Trim().ToLower() == e.CommandArgument.ToString())
lbl_result.Text = "Email values are indentical";
else
{
//Business Layer Call
NewsLetterBL newsBl2 = new NewsLetterBL();
if (newsBl2.ModifyWrongEmail(e.CommandArgument.ToString(), txt_emailNewsletter.Text.Trim().ToLower()))
lbl_result.Text = "Email Changed";
else
lbl_result.Text = "ERROR : " + newsBl2.LastMessage;
}
}
LoadDataForGridView(((GridView)sender));
BindGridView(((GridView)sender), -1, ((GridView)sender).PageIndex);
break;
}
}

How to get the Command Argument on Row Data bound Event of gridview

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);
}
}

Find out a CHECKBOX in a DATAGRID in ASP.NET

I have a GRIDVIEW and with several CHECKBOXS.
When i selected a CHECKBOX I need run some code.
To detect it, I use an EVENT HANDLER for the CHECKBOX included in a GRIDVIEW.
I cannot access the CHECKBOX with my wrong code.
Do you have any idea what I am doing wrong? Thanks for your help. Bye
ASPX
<asp:Label ID="uxMessageDisplayer" runat="server" Visible="False" EnableViewState="False"></asp:Label>
<asp:GridView ID="uxUserListDisplayer" runat="server" AutoGenerateColumns="False"
OnRowDataBound="uxUserListDisplayer_RowDataBound">
<Columns>
<asp:TemplateField HeaderText="Active">
<ItemTemplate>
<asp:CheckBox ID="uxActiveCheckBoxSelector" runat="server" AutoPostBack="true" OnCheckedChanged="uxRoleCheckBoxSelector_CheckChanged" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Users">
<ItemTemplate>
<asp:Label runat="server" ID="uxUserNameLabelDisplayer" Text='<%# Container.DataItem %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="uxLinkEditButton" runat="server" CausesValidation="False" CommandName="Edit"
Text="Edit"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:LinkButton ID="uxLinkDeleteButton" runat="server" CausesValidation="False" CommandName="Delete"
Text="Delete"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
CODE BEHIND
protected void uxRoleCheckBoxSelector_CheckChanged(object sender, EventArgs e)
{
// Reference the CheckBox that raised this event
//CheckBox uxActiveCheckBoxSelector = sender as CheckBox;
CheckBox activeCheckBox = (CheckBox)FindControl("uxActiveCheckBoxSelector");
if (activeCheckBox.Checked == true)
{
uxMessageDisplayer.Text = "T - Aproved User";
uxMessageDisplayer.Enabled = false;
}
else
{
uxMessageDisplayer.Text = "F - NOT Aproved User";
uxMessageDisplayer.Enabled = false;
}
}
If I am not mistaken by your question, you are trying to set the text of the label on the same row with the checkbox based on its checked status.
Below is the code snippet I tried on my pc, hope it helps.
.aspx:
<asp:GridView ID="GridView1" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="CheckBox1" runat="server" OnCheckedChanged="CheckBox1_CheckChanged" AutoPostBack="true" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text=""></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
.cs:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
return;
//create dummy data
List<string> rows = new List<string>();
Enumerable.Range(1, 5).ToList().ForEach(x => rows.Add(x.ToString()));
//bind dummy data to gridview
GridView1.DataSource = rows;
GridView1.DataBind();
}
protected void CheckBox1_CheckChanged(object sender, EventArgs e)
{
//cast sender to checkbox
CheckBox CheckBox1 = (CheckBox)sender;
//retrieve the row where checkbox is contained
GridViewRow row = (GridViewRow)CheckBox1.NamingContainer;
//find the label in the same row
Label Label1 = (Label)row.FindControl("Label1");
//logics
if (CheckBox1 != null) //make sure checkbox1 is found
{
if (CheckBox1.Checked)
{
if (Label1 != null) //make sure label1 is found
{
Label1.Text = "Checked";
}
}
else
{
if (Label1 != null)
{
Label1.Text = "Unchecked";
}
}
}
}
I'm assuming the event handler is actually registered to the checkbox.
CheckBox activeCheckBox = (CheckBox)sender;
what is "uxActiveCheckBoxSelector" and why are you ignoring sender?
Code corrected as suggest!
Usefull resource for beginners
protected void uxRoleCheckBoxSelector_CheckChanged(object sender, EventArgs e)
{
// Cast sender to CheckBox
CheckBox activeCheckBox = (CheckBox)sender;
// Retrieve the row where CheckBox is contained (NamingContainer used to retrive parent control
GridViewRow row = (GridViewRow)activeCheckBox.NamingContainer;
if (activeCheckBox.Checked == true)
{
uxMessageDisplayer.Text = "T - Aproved User";
}
else
{
uxMessageDisplayer.Text = "F - NOT Aproved User";
}
}

Categories

Resources