checked changed event not firing - c#

I am trying to fire the checkbox checkedchanged event but nothing seems to work. Am I missing something here in the following code. I think I have fulfilled all the necessary conditions. So what can be wrong?
<asp:UpdatePanel ID="UpdatePanelApprove" runat="server" RenderMode="Inline" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label runat="server" ID="LabelApproved" Font-Bold="true" ForeColor="Green"></asp:Label>
<asp:CheckBox runat="server" ID="CheckBoxApprove" Text="Approve?" OnCheckedChanged="CheckBoxApprove_CheckedChanged" AutoPostBack="True"/>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID ="CheckBoxApprove" EventName="CheckedChanged" />
</Triggers>
</asp:UpdatePanel>
edit
the code in C#
protected void CheckBoxApprove_CheckedChanged(object sender, EventArgs e)
{
CheckBox CheckBoxApprove = (CheckBox)sender;
GridViewRow row = (GridViewRow)CheckBoxApprove.Parent.Parent.Parent;
HiddenField HiddenFieldAnswerId = (HiddenField)row.FindControl("HiddenFieldAnswerId");
HiddenField HiddenFieldExpertId = (HiddenField)row.FindControl("HiddenFieldExpertId");
Label LabelApproved = (Label)row.FindControl("LabelApproved");
UpdatePanel UpdatePanelApprove =(UpdatePanel) row.FindControl("UpdatePanelApprove");
int AnswerSubjectId = AnswerDataAccess.GetSubjectIdForAnswer(Convert.ToInt32(HiddenFieldAnswerId.Value));
if (!AnswerDataAccess.CheckAnswerApprovalStatus(Convert.ToInt32(HiddenFieldAnswerId.Value)))
{
if (AnswerDataAccess.ApproveAnswer(Convert.ToInt32(HiddenFieldAnswerId.Value)))
{
if (HiddenFieldExpertId.Value != Membership.GetUser().ProviderUserKey.ToString())
{
NotificationsAccess.InsertNotification(AnswerSubjectId, null, Convert.ToInt32(HiddenFieldAnswerId.Value), null, "Approved your answer", new Guid(Membership.GetUser().ProviderUserKey.ToString()), new Guid(HiddenFieldExpertId.Value));
}
LabelApproved.Text = "Approved";
}
}
else
{
if (AnswerDataAccess.DisapproveAnswer(Convert.ToInt32(HiddenFieldAnswerId.Value)))
{
LabelApproved.Text = "";
}
}
UpdatePanelApprove.Update();
}
pageload code
protected void Page_Load(object sender, EventArgs e)
{
HtmlGenericControl Tabs = (HtmlGenericControl)this.Master.FindControl("divTabs");
Tabs.Style[HtmlTextWriterStyle.Display] = "block";
Tabs.Style["border"] = "1px solid #eee";
Tabs.InnerText = "some text";
Tabs.Style["font-size"] = "10px";
if(!IsPostBack )
{
DataTable UserS=ProfileDataAccess.GetUserS (Membership.GetUser().ProviderUserKey.ToString());
DropDownListS.DataSource=UserS;
DropDownListS.DataValueField ="SId";
DropDownListS.DataTextField="Sub";
DropDownListS.DataBind();
ListItem item= new ListItem("Select-s", "0");
item.Selected = true;
DropDownListS.Items.Add(item);
}
}

Het Try this property EnableViewState="true" in checkbox control.

Related

Call Code Behind method (function) in RowCreated Gridview's handler

I want to call a Code Behind method inside a Gridview.
This is the Code Behind method that loops through every webcontrol that’s in the form:
private void SetupJSdataChange(Control parentControl)
{
foreach (Control control in parentControl.Controls)
{
//Response.Write(control.ID + "<br>");
if (control is WebControl)
{
WebControl webControl = control as WebControl;
webControl.Attributes.Add("onchange", "InputChanged(this)");
}
}
}
And I want it to loop through every webcontrol that’s in a RowCreated gridview's handler instead. This is my try:
protected void GVTrabajadores_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
foreach (Control control in parentControl.Controls)
{
//Response.Write(control.ID + "<br>");
if (control is WebControl)
{
WebControl webControl = control as WebControl;
webControl.Attributes.Add("onchange", "InputChanged(this)");
}
}
}
}
But I get an error that says "the name 'parentControl' doesn't exist in the current context" and I don't know how to handle it.
And this is the Gridview:
<asp:GridView ID="GVTrabajadores" runat="server"
CssClass="table table-hover table-striped"
ShowHeaderWhenEmpty = "true"
GridLines="None"
AutoGenerateColumns="False"
ShowFooter="true"
OnRowCreated="GVTrabajadores_RowCreated"
OnRowCommand="GVTrabajadores_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Nombre">
<ItemTemplate>
<asp:TextBox ID="TxNombre" runat="server" Text='<%#Eval("nombre") %>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TxNombref" runat="server" />
</FooterTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Cerrada">
<ItemTemplate>
<asp:CheckBox ID="CBCerrada" runat="server" Checked='<%# (Eval("cerrada").ToString() == "1" ? true : false) %>' />
</ItemTemplate>
<FooterTemplate>
<asp:CheckBox ID="CBCerradaf" runat="server" />
</FooterTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
This should work for you. Note that I used generic event args - if you need them you'll need to change them.
private void GVTrabajadores_RowCreated(object sender, GridViewRowEventArgs e)
{
GridView gV = sender as GridView;
for(int i = 0; i < gV.Columns.Count; i++)
{
Control c = e.Row.Cells[i].Controls[0];
string controlType = c.GetType().ToString().Replace("System.Web.UI.WebControls.", "");
switch (controlType)
{
case "TextBox":
TextBox t = c as TextBox;
t.TextChanged += GVTrabajadores_TextBox_TextChanged;
t.AutoPostBack = true;
break;
case "CheckBox":
CheckBox cB = c as CheckBox;
cB.CheckedChanged += GVTrabajadores_CheckBox_Changed;
cB.AutoPostBack = true;
break;
}
}
}
private void GVTrabajadores_CheckBox_Changed(object sender, EventArgs e)
{
//process change
}
private void GVTrabajadores_TextBox_TextChanged(object sender, EventArgs e)
{
//process changed text
}

ASP.NET Repeater not binding

I have issues.
One of them is this one.
I'm trying to bind a list of Hyperlinks to a repeater and I think my code looks all good, but my repeater is sadly lacking in anything. It's totally blank (Apart from the header, which is not databound).
I can't see where the problem is, so I'm hoping you guys can point it out to me.
Code:
Markup
<asp:Panel ID="pnlNavMenu" class="navigation" runat="server" Visible="true">
<div class="search-textbox"><div>
<asp:ImageButton ID="btnSearch" class="Search-Icon"
BackColor="White" runat="server" OnClick="btnSearch_Click"
ImageUrl="~/images/Mobile/mobile-search-icon.png" />
<asp:TextBox ID="txtSearch" runat="server" CssClass="Search" onblur="if(this.value == '') { this.value='Enter keyword or product code'; isSet=true; }"
onmouseover="if(this.value == 'Enter keyword or product code') { this.value='';isSet = true; }"
onmouseout="if(this.value == '' && !isSet) { this.value='Enter keyword or product code'; isSet=>false; }"
MaxLength="255" Text="Enter keyword or product code" ontextchanged="btnSearch_Click"/>
<asp:ImageButton ID="btnClear" class="Search-Cancel" BackColor="White" runat="server" OnClick="btnClear_Click" ImageUrl="~/images/Mobile/mobile-search-cancel.png" />
</div>
</div>
<asp:Panel ID="pnlComputers" runat="server" CssClass="nav-item" Visible="true">
<asp:Label id="lblComp" Text="Computers" runat="server" cssclass="Menu-Panel-Header"></asp:Label>
<asp:Repeater ID="rptComputers" runat="server">
<ItemTemplate><asp:HyperLink ID="hlCompCategories" runat="server" CssClass="nav-sub-item"><%#Eval("XW_WEBCATNAME") %></asp:HyperLink></ItemTemplate>
</asp:Repeater>
</asp:Panel
<asp:CollapsiblePanelExtender ID="cpe1" runat="Server" TargetControlID="pnlComputers" CollapsedSize="64" ExpandedSize="192" Collapsed="True" ExpandControlID="lblComp" CollapseControlID="lblComp" AutoCollapse="false" AutoExpand="False" ScrollContents="True" ExpandDirection="Vertical" />
</asp:Panel>
C#
protected void Page_Init(object sender, EventArgs e)
{
if (Session["Customer"] is GPCUser)
{
hlLogInOut.Text = "Log Out";
hlLogInOut.NavigateUrl = "log-in.aspx?logout=1";
hlRegDetails.Text = "My Details";
hlRegDetails.NavigateUrl = "/update-details.aspx";
}
else
{
hlLogInOut.Text = "Log in";
hlLogInOut.NavigateUrl = "/log-in.aspx";
hlRegDetails.Text = "Register";
hlRegDetails.NavigateUrl = "/create-account.aspx";
}
BindCategories();
}
private void BindCategories()
{
if (!IsPostBack)
{
try
{
SqlConnection connect = new SqlConnection();
DataTable Data = new DataTable();
connect.ConnectionString = "SERVER = SERVER-SQL01; Trusted_Connection=yes; DATABASE=PCSQL";
connect.Open();
string query = null;
query = "SELECT * from dbo.STOCK_GROUPS WHERE XW_MAINGROUP = '1' ORDER BY XW_WEBCATNAME ASC";
SqlDataAdapter command = new SqlDataAdapter(query, connect);
command.Fill(Data);
connect.Close();
rptComputers.DataSource = Data;
}
catch (SqlException sqlEX)
{
sqlEX.ToString();
}
}
}
protected void rptComputers_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item | e.Item.ItemType == ListItemType.AlternatingItem)
{
HyperLink hlCompCategories = (HyperLink)e.Item.FindControl("hlCompCategories");
DataRowView dr = (DataRowView)e.Item.DataItem;
hlCompCategories.NavigateUrl = Page.ResolveUrl("~/" + "Computers" + "/" + dr["XW_URL"] + "/index.aspx");
if ((!object.ReferenceEquals(dr["xw_webcatname"], System.DBNull.Value)))
{
hlCompCategories.Text = (dr["xw_webcatname"]).ToString();
hlCompCategories.ToolTip = (dr["xw_webcatname"]).ToString();
}
else
{
hlCompCategories.Text = dr["groupname"].ToString();
hlCompCategories.ToolTip = dr["xw_webcatname"].ToString();
}
}
}
I'm pretty sure that the issue is in the ItemDataBound method because the rest of the panel loads fine (search bar and header, etc.) but none of my links are there.
After
rptComputers.DataSource = Data;
add
rptComputers.DataBind();
Otherwise it won't bind.
You might be missing AutoEventWireup=true in Page header in aspx file.
If not than please try to bind the repeater in the Page_Load event instead binding in Page_Init event.

Pass value from a Repeater row to a textbox on button click in asp.net C#

I have the following repeater wrapped in an Update Panel
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DropDownList1" EventName="SelectedIndexChanged" />
</Triggers>
<ContentTemplate>
<asp:Repeater ID="skillTable" runat="server">
<ItemTemplate>
<table class="table table-hover">
<tr>
<td>
<asp:ImageButton runat="server" AutoPostBack="True" ID="skillButton" OnClick="skillButton_Click" CommandArgument="<%# Eval(DropDownList1.SelectedValue)%>" class="addText btn btn-success" ImageUrl="~/img/addbut.png" /></td>
<td><asp:Label runat="server" id="skillName" Text='<%# DataBinder.Eval(Container.DataItem, DropDownList1.SelectedValue) %>'></asp:Label></td>
</tr>
</table>
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
It kicks out the information from my database perfectly, and it has a button right before the text in each row.
The problem that i have is that I need each button on each row to, when clicked, add the specific line of code in that row to a textbox.
foreach (RepeaterItem item in skillTable.Items)
{
string skill = item.DataItem.ToString();
string text = skillList.Text;
if (!string.IsNullOrEmpty(text))
{
if (!text.Contains(skill))
{
text += " | " + skill;
skillList.Text = text;
}
}
else
{
text = skill;
skillList.Text = text;
}
}
UpdatePanel2.Update();
I have also tried this way,
protected void skillTable_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
int d = 0;
if(DropDownList1.SelectedValue == "Business and Finance")
{
d = 1;
}
else if(DropDownList1.SelectedValue == "Computers and Technology")
{
d = 2;
}
else if (DropDownList1.SelectedValue == "Education")
{
d = 3;
}
else if (DropDownList1.SelectedValue == "Customer Service")
{
d = 4;
}
DataRowView drv = (DataRowView)e.Item.DataItem;
string skill = drv[d].ToString();
Session["Table"] = skill;
}
protected void skillButton_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
string skill = (string)(Session["Table"]);
string text = skillList.Text;
if (!string.IsNullOrEmpty(text))
{
if (!text.Contains(skill))
{
text += " | " + skill;
skillList.Text = text;
}
}
else
{
text = skill;
skillList.Text = text;
}
UpdatePanel2.Update();
}
but neither one of them seems to work correctly. Any advice? I havent really used repeaters before this, so If there is any other tool that would work better, I'm open for suggestions.
Thanks in advance!
So I figured it out. What I was missing was a way for my site to specifically narrow down what i needed. I added the code blow to my click method and got rid of the ItemDataBound method and it worked like a charm.
Button button = (sender as Button);
string commandArgument = button.CommandArgument;
RepeaterItem item = button.NamingContainer as RepeaterItem;
var workText = (Label)item.FindControl("workName1") as Label;
string work = workText.Text;
string text = workDetails1.Text;
if (text == " ")
text = "";
if (text == "")
{
if (!text.Contains(work))
{
text +="\u2022 " + work;
workDetails1.Text = text;
}
}
else if (!string.IsNullOrEmpty(work))
{
if (!text.Contains(work))
{
text += "\n\u2022 " + work;
workDetails1.Text = text;
}
else
{
workDetails1.Text = text;
}
}
UpdatePanel4.Update();
Hope this helps someone!

How to fire click event of the LinkButton in gridview and Show PopUp window in asp.net

I have tried to build one gridview with dynamic columns based the data source using the template fields in asp.net through code behind.
For that, to implement we have developed one class DynamicTemplate which implements the ITemplate interface. In that template fields i have inserted the LinkButton in each cell and when i click that cell link button i need to show the one Popup with selected cell value.
For Detailed Sample Please download from this link
For that I have created one Default.asxp page and wrote the following.
public partial class Default : System.Web.UI.Page
{
DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GenateGridView();
}
private void GenateGridView()
{
TemplateField tempField;
DynamicTemplate dynTempItem;
LinkButton lnkButton;
Label label;
GridView gvDynamicArticle = new GridView();
gvDynamicArticle.Width = Unit.Pixel(500);
gvDynamicArticle.BorderWidth = Unit.Pixel(0);
gvDynamicArticle.Caption = "<div>Default Grid</div>";
gvDynamicArticle.AutoGenerateColumns = false;
DataTable data = getBindingData();
for (int i = 0; i < data.Columns.Count; i++)
{
tempField = new TemplateField();
dynTempItem = new DynamicTemplate(ListItemType.AlternatingItem);
lnkButton = new LinkButton();
lnkButton.ID = string.Format("lnkButton{0}", i);
lnkButton.Visible = true;
string ColumnValue = data.Columns[i].ColumnName;
tempField.HeaderText = ColumnValue;
if (ColumnValue == "EmpName")
{
label = new Label();
label.ID = string.Format("Label{0}", i);
dynTempItem.AddControl(label, "Text", ColumnValue);
label.Width = 100;
}
else
{
dynTempItem.AddControl(lnkButton, "Text", ColumnValue);
lnkButton.Click += lnkButton_Click;
}
tempField.ItemTemplate = dynTempItem;
gvDynamicArticle.Columns.Add(tempField);
//////grdUserPivotDateTwo.Columns.Add(tempField);
}
gvDynamicArticle.DataSource = data;
gvDynamicArticle.DataBind();
divContainer.Controls.Add(gvDynamicArticle);
}
void lnkButton_Click(object sender, EventArgs e)
{
// showing cell values in popUp here..
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('cell clicked')");
}
private DataTable getBindingData()
{
dt = new DataTable();
dt.Columns.Add(new DataColumn("EmpName"));
dt.Columns.Add(new DataColumn("Monday"));
dt.Columns.Add(new DataColumn("TuesDay"));
dt.Columns.Add(new DataColumn("WednesDay"));
dt.Columns.Add(new DataColumn("ThursDay"));
dt.Rows.Add("EmpOne", "p", "p", "p", "a");
dt.Rows.Add("EmpTwo", "p", "a", "p", "p");
dt.Rows.Add("EmpThree", "p", "p", "p", "a");
dt.Rows.Add("EmpFour", "p", "a", "p", "p");
dt.Rows.Add("EmpFive", "p", "p", "p", "a");
dt.Rows.Add("EmpSix", "a", "p", "p", "p");
return dt;
}
}
and corresponding DynamicTemplate class is
public class DynamicTemplate : System.Web.UI.ITemplate
{
System.Web.UI.WebControls.ListItemType templateType;
System.Collections.Hashtable htControls = new System.Collections.Hashtable();
System.Collections.Hashtable htBindPropertiesNames = new System.Collections.Hashtable();
System.Collections.Hashtable htBindExpression = new System.Collections.Hashtable();
public DynamicTemplate(System.Web.UI.WebControls.ListItemType type)
{
templateType = type;
}
public void AddControl(WebControl wbControl, String BindPropertyName, String BindExpression)
{
htControls.Add(htControls.Count, wbControl);
htBindPropertiesNames.Add(htBindPropertiesNames.Count, BindPropertyName);
htBindExpression.Add(htBindExpression.Count, BindExpression);
}
public void InstantiateIn(System.Web.UI.Control container)
{
PlaceHolder ph = new PlaceHolder();
for (int i = 0; i < htControls.Count; i++)
{
//clone control
Control cntrl = CloneControl((Control)htControls[i]);
switch (templateType)
{
case ListItemType.Header:
break;
case ListItemType.Item:
ph.Controls.Add(cntrl);
break;
case ListItemType.AlternatingItem:
ph.Controls.Add(cntrl);
ph.DataBinding += new EventHandler(Item_DataBinding);
break;
case ListItemType.Footer:
break;
}
}
ph.DataBinding += new EventHandler(Item_DataBinding);
container.Controls.Add(ph);
}
public void Item_DataBinding(object sender, System.EventArgs e)
{
PlaceHolder ph = (PlaceHolder)sender;
GridViewRow ri = (GridViewRow)ph.NamingContainer;
for (int i = 0; i < htControls.Count; i++)
{
if (htBindPropertiesNames[i].ToString().Length > 0)
{
Control tmpCtrl = (Control)htControls[i];
String item1Value = (String)DataBinder.Eval(ri.DataItem, htBindExpression[i].ToString());
Control ctrl = ph.FindControl(tmpCtrl.ID);
Type t = ctrl.GetType();
System.Reflection.PropertyInfo pi = t.GetProperty(htBindPropertiesNames[i].ToString());
pi.SetValue(ctrl, item1Value.ToString(), null);
}
}
}
private Control CloneControl(System.Web.UI.Control src_ctl)
{
Type t = src_ctl.GetType();
Object obj = Activator.CreateInstance(t);
Control dst_ctl = (Control)obj;
PropertyDescriptorCollection src_pdc = TypeDescriptor.GetProperties(src_ctl);
PropertyDescriptorCollection dst_pdc = TypeDescriptor.GetProperties(dst_ctl);
for (int i = 0; i < src_pdc.Count; i++)
{
if (src_pdc[i].Attributes.Contains(DesignerSerializationVisibilityAttribute.Content))
{
object collection_val = src_pdc[i].GetValue(src_ctl);
if ((collection_val is IList) == true)
{
foreach (object child in (IList)collection_val)
{
Control new_child = CloneControl(child as Control);
object dst_collection_val = dst_pdc[i].GetValue(dst_ctl);
((IList)dst_collection_val).Add(new_child);
}
}
}
else
{
dst_pdc[src_pdc[i].Name].SetValue(dst_ctl, src_pdc[i].GetValue(src_ctl));
}
}
return dst_ctl;
}
}
Here the Data showing in gridview is fine. Here the Issues are when i click on the linkButton the page reloads and no grid is displaying after the postback.
second issue is, for LinkButton the Click Event is not firing.
Please provide me the help full information/Sample to show the modal window when we click on the linkButton of the gridview.
You need to use ajax model popup expender.
Design a panel with your fields and use the model popup expender to display that popup
This link has the sample of it
www.asp.net/ajaxlibrary/ajaxcontroltoolkitsamplesite/modalpopup/modalpopup.aspx
and in your link button click
you have to use show method to open popup
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GenateGridView();
}
this code is generating a gridview only if it is not a postback, but when you click a linkbutton a postpack occurs and that's the reason why gridview doesnt show again when you click on the linkbutton.
add the following code(additional else part included to your if code) to show gridview when you click lnkButton
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
GenateGridView();
else
{
string ctrlName = Request.Params.Get("__EVENTTARGET").Trim();
if (!String.IsNullOrEmpty(ctrlName))
{
if (ctrlName.StartsWith("lnkButton"))
{
GenateGridView();
}
}
}
}
It will be a good choice to use CommandName property for the linkbutton on the Gridview and give it a specfic name and in the code file and exactly work with it in RowCommand event of your GridView as following in this example :
first here is the .aspx file :
<div>
<asp:GridView ID="GridViewStudents" runat="server" AutoGenerateColumns="False" OnRowCommand="GridViewStudents_RowCommand">
<Columns>
<asp:TemplateField HeaderText="Stud_ID" Visible="False">
<ItemTemplate>
<asp:Label ID="LabelStudID" runat="server" Text='<%# Eval("Stud_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="FKFather_ID" Visible="False">
<ItemTemplate>
<asp:Label ID="LabelFkFatherID" runat="server" Text='<%# Eval("Fk_Father_ID") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Student Name">
<ItemTemplate>
<asp:Label ID="LabelStudName" runat="server" Text='<%# Eval("Stud_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Class Name">
<ItemTemplate>
<asp:Label ID="LabelRowlevelName" runat="server" Text='<%# Eval("Stud_Level_Row_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Delete">
<ItemTemplate>
<asp:ImageButton ID="ImageButtonDelete" runat="server" CommandArgument='<%# Eval("Stud_ID") %>' CommandName="Remove" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
<div style="direction: ltr">
<asp:Panel ID="Panel1" runat="server" Visible="false">
<asp:Label ID="Labelpopupmessage" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="Buttonaccept" runat="server" Text="نعم" OnClick="Buttonaccept_Click" />
<asp:Button ID="Buttoncancel" runat="server" Text="لا" OnClick="Buttoncancel_Click" />
</asp:Panel>
<asp:HiddenField ID="HiddenField1" runat="server" />
<asp:ModalPopupExtender runat="server" ID="ModalPopupExtenderStudent" PopupControlID="ButtonSubmit" TargetControlID="HiddenField1" CancelControlID="Buttoncancel">
</asp:ModalPopupExtender>
</div>
and here is the code implementation of my illustration :
protected void GridViewStudents_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Remove")
{
// I stored the ID of the selected Student I want to delete in a viewstate.
ViewState.Add("DeletedStudDetailID",Convert.ToInt32(e.CommandArgument));
ModalpopupExtender.Show();
}
}
// Here in the accept delete button I used that code ..
protected void Buttonaccept_Click(object sender, EventArgs e)
{
try
{
if (ViewState["DeletedStudDetailID"] != null)
{
StudentDetail StudDet = Data.StudentDetails.Single(SD => SD.Fk_Stud_ID == Convert.ToInt32(ViewState["DeletedStudDetailID"]));
Data.StudentDetails.DeleteOnSubmit(StudDet);
Student Stud = Data.Students.Single(S => S.Stud_ID == Convert.ToInt32(ViewState["DeletedStudDetailID"]));
Data.Students.DeleteOnSubmit(Stud);
Data.SubmitChanges();
}
this.ResultMessage = "Delete Done Sucessfully !!";
}
catch
{
this.ErrorMessage = "Delete operation disordered !!";
}
finally
{
ModalPopExtender.Hide();
}
}
I hope it helps in your issue and I wish you a happy day :) !!
First, your GridView will be created when calling GenateGridView method, so you have to call this method everytime you do post back, then your Page_Load should be
protected void Page_Load(object sender, EventArgs e)
{
GenateGridView();
}
Second, I would present you the other way to add LinkButton to GridView dynamically.
I modified your GenateGridView to just add only label into DynamicTemplate, also add this line gvDynamicArticle.RowDataBound += new GridViewRowEventHandler(gvDynamicArticle_RowDataBound); to handle adding LinkButton.
private void GenateGridView()
{
TemplateField tempField;
DynamicTemplate dynTempItem;
Label label;
GridView gvDynamicArticle = new GridView();
gvDynamicArticle.Width = Unit.Pixel(500);
gvDynamicArticle.BorderWidth = Unit.Pixel(0);
gvDynamicArticle.Caption = "<div>Default Grid</div>";
gvDynamicArticle.AutoGenerateColumns = false;
gvDynamicArticle.RowDataBound += new GridViewRowEventHandler(gvDynamicArticle_RowDataBound);
DataTable data = getBindingData();
for (int i = 0; i < data.Columns.Count; i++)
{
tempField = new TemplateField();
dynTempItem = new DynamicTemplate(ListItemType.AlternatingItem);
string ColumnValue = data.Columns[i].ColumnName;
tempField.HeaderText = ColumnValue;
label = new Label();
label.ID = string.Format("Label{0}", i);
dynTempItem.AddControl(label, "Text", ColumnValue);
label.Width = 100;
tempField.ItemTemplate = dynTempItem;
gvDynamicArticle.Columns.Add(tempField);
}
gvDynamicArticle.DataSource = data;
gvDynamicArticle.DataBind();
divContainer.Controls.Add(gvDynamicArticle);
}
I implement like this in RowDataBound event handler of the GridView to add LinkButton and hide the Label which we added it before:
protected void gvDynamicArticle_RowDataBound(object sender, GridViewRowEventArgs e)
{
for (int j = 1; j < e.Row.Cells.Count; j++)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
LinkButton lnkButton = new LinkButton();
lnkButton.ID = string.Format("lnkButton{0}{1}", e.Row.DataItemIndex, j);
lnkButton.Click += new EventHandler(lnkButton_Click);
Label tempLabel = e.Row.FindControl("Label" + j) as Label;
lnkButton.Text = tempLabel.Text;
lnkButton.CommandArgument = tempLabel.Text;
tempLabel.Visible = false;
e.Row.Cells[j].Controls.Add(lnkButton);
}
}
}
You can also set any value to CommandArgument of LinkButton, then you can show it in the alert.
Final, seems you want to show some value in the alert, you may code like this
public void lnkButton_Click(object sender, EventArgs e)
{
// showing cell values in popUp here..
LinkButton lnk = (LinkButton)sender;
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('cell clicked, value " + lnk.CommandArgument + "')", true);
}

Connect HyperLinkField click to Server-side method (c#)

I have a HyperLinkField which I populate with the urls from a datatable, the field in the datatable is called EncodedAbsUrl.
However, I want to connect this link to a code behind method instead
What I do now
var encodedAbsUrl = new string[] { "EncodedAbsUrl" };
var hf = new HyperLinkField
{
HeaderText = "Link",
DataTextField = "ServerUrl",
DataNavigateUrlFields = encodedAbsUrl,
DataNavigateUrlFormatString = "{0}",
Target = "_blank",
};
But id like to do something like this
var encodedAbsUrl = new string[] { "EncodedAbsUrl" };
var hf = new HyperLinkField
{
HeaderText = "Link",
DataTextField = "ServerUrl",
NavigateUrl = clicker(encodedAbsUrl["{0}"]),
Target = "_blank",
};
protected void clicker(string url)
{
//...
}
Well you can see my attempts are unsuccessful :)
Any advice is appreciated
Thanks!
if you will use HyperLinkField so you will not need to Clicker or any postback event because this field will be rendered as <a> tag. I made a sample example using HyperLink control and LinkButton control that will be postback your page.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
gv.DataSource = [YourDataSource];
gv.DataBind();
}
}
protected void Clicker(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Link")
{
Response.Redirect(e.CommandArgument.ToString());
}
}
protected void gv_DataBinding(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
HyperLink hlink = e.Row.FindControl("hlink") as HyperLink;
hlink.NavigateUrl = ((Person)e.Row.DataItem).NavUrl;
hlink.Text = ((Person)e.Row.DataItem).NavUrl;
hlink.Target = "_blank";
LinkButton lnkButton = e.Row.FindControl("lnkButton") as LinkButton;
lnkButton.Text = ((Person)e.Row.DataItem).NavUrl;
lnkButton.CommandName = "Link";
lnkButton.CommandArgument = ((Person)e.Row.DataItem).NavUrl;
}
}
you GridView will like this
<asp:GridView runat="server" ID="gv" OnRowCommand="Clicker" OnRowDataBound="gv_DataBinding"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink runat="server" ID="hlink"></asp:HyperLink>
<asp:LinkButton runat="server" ID="lnkButton"></asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
You'll need to use a LinkButton if you want to be able to postback to the server in the way you require.
This class has an OnClick event unlike the HyperLinkField you've been using.
You can find out more info about the LinkButton class here.

Categories