.NET UpdatePanel and FaceBook / Twitter Buttons - c#

I have an UpdatePanel which has a gridview inside it. On each of the gridviewrows, within the gridview, I have a Twitter and FaceBook button.
The gridview renders fine with the buttons on page load, however, once a partial postback is done on the updatepanel the Twitter and FaceBook buttons do not render.
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<!-- search controls.... -->
<asp:ImageButton ID="btnSearch" ImageUrl="~/img/button-search.gif" runat="server" />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" EnableModelValidation="True"
BorderStyle="None" Font-Size="Small" GridLines="None" AllowPaging="True" ShowFooter="True"
Width="100%" OnPageIndexChanging="GridView1_PageIndexChanging">
<RowStyle CssClass="row1" />
<AlternatingRowStyle CssClass="row2" />
<Columns>
<asp:TemplateField>
<ItemTemplate>
...
<asp:TemplateField>
<ItemTemplate>
<asp:Literal ID="ltlTwitter" runat="server" Text='<%# GetTwitterURL(Eval("ID"), Eval("SomeText")) %>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Literal ID="ltlFacebook" runat="server" Text='<%# GetFacebookURL(Eval("ID")) %>'></asp:Literal>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" Visible="False" />
</Columns>
<EmptyDataTemplate>
<strong>There are no offers for this search criteria.</strong>
</EmptyDataTemplate>
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID="btnSearch" />
</Triggers>
</asp:UpdatePanel>
Relevant C#:
public static string GetTwitterURL(object ID, object text)
{
...
StringBuilder sb = new StringBuilder();
sb.Append("<div>");
sb.Append("<a href=\"http://twitter.com/share\" " +
"class=\"twitter-share-button\" ");
sb.AppendFormat("data-url=\"{0}?ID={1}\" ", obj.Property, oID.ToString());
sb.Append("data-via=\"xxx\" ");
sb.AppendFormat("data-text=\"{0}\"", xxx);
sb.Append("data-count=\"none\">Tweet</a>");
sb.Append("</div>");
return sb.ToString();
}
public static string GetFacebookURL(object OfferID)
{
...
return string.Format("<fb:like href=\"{0}?ID={1}\" " +
"send=\"false\" layout=\"button_count\" show_faces=\"false\" " +
"action=\"like\" font=\"tahoma\"></fb:like>", obj.Property, someInt);
}
Also, the page in question is a child page of a master page.
Here is the additional code-behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindOffersGrid(true);
}
}
public List<Offer> CurrentOffersDataSet
{
get
{
object o = ViewState["CurrentOfferDataSet"];
return (o == null ? new List<Offer>() : (List<Offer>)o);
}
set
{
ViewState["CurrentOfferDataSet"] = value;
}
}
protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = this.CurrentOffersDataSet;
GridView1.DataBind();
}
private void BindOffersGrid(bool ApplyRandomSort)
{
List<Offer> lstOffers = Offers.GetAllBySearchCriteria(
Convert.ToInt32(ddlOfferCounty.SelectedValue),
Convert.ToInt32(ddlOfferTypes.SelectedValue),
Convert.ToDateTime(ddlOfferDate.SelectedValue), -1, true);
...
//Some filtering of the dataset with Linq
...
GridView1.DataSourceID = string.Empty;
this.CurrentOffersDataSet = lstFilteredOffers.
OrderByDescending(a => a.IsExclusive).
ThenBy(a => Guid.NewGuid()).
ToList();
GridView1.DataSource = this.CurrentOffersDataSet;
GridView1.DataBind();
}

Ok, I added the following code at the very end of my child page and now the Twitter and FaceBook like button are appearing after partial postbacks.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_pageLoaded(pageLoaded);
var _panels, _count;
function pageLoaded(sender, args) {
if (_panels != undefined && _panels.length > 0) {
for (i = 0; i < _panels.length; i++)
_panels[i].dispose();
}
var panels = args.get_panelsUpdated();
if (panels.length > 0) {
updateFbLike();
}
}
function updateFbLike() {
$.getScript("http://platform.twitter.com/widgets.js");
FB.XFBML.parse();
}
</script>

Related

Hide/show gridview column based on role

Want to be able to set an "Edit" linkbutton to visible=false unless the user has a role of "Editor".
Been poking around stackoverflow and elsewhere and so far have not been able to get this to work.
Gridview:
<asp:GridView ID="GridView1" runat="server" Caption="Questions Awaiting Review" AllowSorting="True" PagerSettings-Mode="NumericFirstLast"
OnPageIndexChanging="GridView1_PageIndexChanging" CaptionAlign="Top" EmptyDataText="No Questions Pending Review."
PageSize="10" AllowPaging="true" PagerStyle-HorizontalAlign="Center" PagerStyle-Font-Size="Large" DataKeyNames="QuestionID"
OnRowCommand="GridView1_RowCommand" AutoGenerateColumns="false" AlternatingRowStyle-BackColor="#cccccc"
OnPreRender="GridView1_OnPreRender">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="QuestionID" runat="server" Text='<%# Eval("QuestionID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="KeyObjective" HeaderText="Key Objective" ItemStyle-Width="250" />
<asp:BoundField DataField="SubmitDate" HeaderText="Submitted Date" ItemStyle-Width="60" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Details" CommandArgument='<%# Eval("QuestionID") %>' runat="server" CommandName="viewQuestion">View Question</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Edit" CommandArgument='<%# Eval("QuestionID") %>' runat="server" CommandName="editQuestion">Edit Question</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Have changed the code behind to use OnPreRender for the gridview, which if the value is hardcoded hides the column. However when I try to retrieve the is in role of editor then the value does not seem to be evaluating correctly. Always returns false even when the user has a role of Editor.
protected void GridView1_OnPreRender(object sender, EventArgs e)
{
if (Roles.IsUserInRole("Editor"))
{
// Enter correct column index.
GridView1.Columns[4].Visible = true;
}
else
{
GridView1.Columns[4].Visible = false;
}
}
Hoping I'm missing something simple, new to asp.net so not unlikely.
Hide last column.
this.GridView1.Columns[this.GridView1.Columns.Count - 1].Visible = Roles.IsUserInRole("Editor");
You want to show/hide an entire column instead of LinkButton control. Otherwise, unauthorized user will always see a column with blank cells which is odd.
The following example will hide an entire column.
Screen Shot (Authorize vs Unauthorized)
ASPX
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoWebForm.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1"
runat="server"
DataKeyNames="QuestionID"
OnPreRender="GridView1_OnPreRender"
AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label ID="QuestionID" runat="server" Text='<%# Eval("QuestionID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="KeyObjective" HeaderText="Key Objective" ItemStyle-Width="250" />
<asp:TemplateField>
<ItemTemplate>
<asp:LinkButton ID="Edit" CommandArgument='<%# Eval("QuestionID") %>'
runat="server" CommandName="editQuestion">Edit Question</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</form>
</body>
</html>
Code Behind
public class Question
{
public int QuestionID { get; set; }
public string KeyObjective { get; set; }
}
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource = new List<Question>
{
new Question {QuestionID = 1, KeyObjective = "One"},
new Question {QuestionID = 2, KeyObjective = "Two"},
new Question {QuestionID = 3, KeyObjective = "Three"},
};
GridView1.DataBind();
}
}
protected void GridView1_OnPreRender(object sender, EventArgs e)
{
bool isEditor = true; // Business logic here
if (isEditor)
{
// Enter correct column index.
GridView1.Columns[2].Visible = false;
}
}
}
Use the LinkButton like this, with the Visibility property set from a function in code behind.
<asp:LinkButton ID="Edit" Visible='<%# ShowEditBasedOnRole() %>' CommandArgument='<%# Eval("QuestionID") %>' runat="server" CommandName="editQuestion">Edit Question</asp:LinkButton>
And then in code behind the function that returns a bool
public bool ShowEditBasedOnRole()
{
if (Roles.IsUserInRole("Editor"))
{
return true;
}
else
{
return false;
}
}
One quick modification instead of accessing the column by index. it can be accessed using header text which would not affect the code even if new column is inserted before the accessed column in future the code snippet
protected void grdResults_OnPreRender(object sender, EventArgs e)
{
TemplateField FieldToAccess= grdResults.Columns.OfType<TemplateField>
().Where(f => f.HeaderText ==
"ValidityDate").FirstOrDefault();
if (role)
FieldToAccess.Visible = false;
}

Display nested gridview

I have a nested GridView with 4 levels,
when i click in "+" to show child GridView i make request to database to download data of current row, every thing work well for me, the only problem i have is in design, all the child GridView display in column of its parent GridView
this is how it looks:
Parent GridView
First Child gridView
here is my aspx code:
<asp:UpdatePanel ID="upNestedGridView" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gvCostCenters" runat="server" ....>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgShowAccountingPlan" runat="server" OnClick="Show_Hide_AccountingPlansGrid" .../>
<asp:Panel ID="pnlAccountingPlan" runat="server" Visible="false" Style="position: relative">
<asp:GridView ID="gvAccountingPlans" runat="server" AutoGenerateColumns="false"....">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgShowPrograms" runat="server" OnClick="Show_Hide_ProgramsGrid" .../>
<asp:Panel ID="pnlPrograms" runat="server" Visible="false" Style="position: relative">
<asp:GridView ID="gvPrograms" runat="server" AutoGenerateColumns="false" ...>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgShowProjects" runat="server" OnClick="Show_Hide_ProjectsGrid" ..../>
<asp:Panel ID="pnlProjects" runat="server" Visible="false" Style="position: relative">
<asp:GridView ID="gvProject" runat="server" ....>
.....
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Label" HeaderText="البند " ItemStyle-HorizontalAlign="Right" />
....
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="NumAccountingPlan" HeaderText="الخطة المحاسبية " ItemStyle-HorizontalAlign="Right" />
...
</Columns>
</asp:GridView>
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
...
<asp:BoundField DataField="OperatingExpenses" HeaderText="المصروفات التشغيلية" DataFormatString="{0:#,##0.00;(#,##0.00);0}" />
</Columns>
</asp:GridView>
my jquery code:
<script type="text/javascript">
$(function () {
$("[src*=minus]").each(function () {
$(this).closest("tr").after("<tr><td></td><td colspan = '999'>" + $(this).next().html() + "</td></tr>");
$(this).next().remove()
});
});
</script>
My code C#:
protected void Show_Hide_AccountingPlansGrid(object sender, EventArgs e)
{
try
{
ServiceClass service = new ServiceClass();
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
_budget = service.GetBudgetById(int.Parse(hfIdBudget.Value));
row.FindControl("pnlAccountingPlan").Visible = true;
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "/Content/img/minus.gif";
string idCostCenter = gvCostCenters.DataKeys[row.RowIndex].Value.ToString();
GridView gvAccountingPlans = row.FindControl("gvAccountingPlans") as GridView;
//gvAccountingPlans.ToolTip = costCenterId;
gvAccountingPlans.DataSource = AccountingPlanData(int.Parse(hfIdUser.Value), int.Parse(hfIdBudget.Value), int.Parse(idCostCenter));
gvAccountingPlans.DataBind();
}
else
{
row.FindControl("pnlAccountingPlan").Visible = false;
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "/Content/img/plus.gif";
}
}
catch (Exception ex) { GlobalHelpers.Trace(ex); }
}
I notice that when i delete the UpdatePanel the first child GridView display well, but the others no.
How can i do to display all childs GridView well?
I'm sorry for my bad english
Code asp:
<asp:UpdatePanel ID="upNestedGridView" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gvCostCenters" runat="server" AutoGenerateColumns="false" ....>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:ImageButton ID="imgShowAccountingPlan" runat="server" OnClick="Show_Hide_AccountingPlansGrid" ImageUrl="/Content/img/plus.gif" CommandArgument="Show" />
</ItemTemplate>
</asp:TemplateField>
....
<asp:TemplateField>
<ItemTemplate>
<tr visible="false" runat="server" id="trAccountingPlan">
<td visible="false" runat="server" id="tdAccountingPlan2"></td>
<td colspan="999" visible="false" runat="server" id="tdAccountingPlan">
<asp:GridView ID="gvAccountingPlans" runat="server" ....>
<Columns>
.....
</Columns>
</asp:GridView>
</td>
</tr>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</ContentTemplate>
Code C#:
protected void Show_Hide_AccountingPlansGrid(object sender, EventArgs e)
{
try
{
ImageButton imgShowHide = (sender as ImageButton);
GridViewRow row = (imgShowHide.NamingContainer as GridViewRow);
if (imgShowHide.CommandArgument == "Show")
{
...
imgShowHide.CommandArgument = "Hide";
imgShowHide.ImageUrl = "/Content/img/minus.gif";
row.FindControl("trAccountingPlan").Visible = true;
HtmlTableCell tdAccountingPlan = (HtmlTableCell)row.FindControl("tdAccountingPlan");
HtmlTableCell tdAccountingPlan2 = (HtmlTableCell)row.FindControl("tdAccountingPlan2");
tdAccountingPlan2.Visible = true;
tdAccountingPlan.Visible = true;
...
}
else
{
imgShowHide.CommandArgument = "Show";
imgShowHide.ImageUrl = "/Content/img/plus.gif";
row.FindControl("trAccountingPlan").Visible = false;
HtmlTableCell tdAccountingPlan = (HtmlTableCell)row.FindControl("tdAccountingPlan");
HtmlTableCell tdAccountingPlan2 = (HtmlTableCell)row.FindControl("tdAccountingPlan2");
tdAccountingPlan2.Visible = false;
tdAccountingPlan.Visible = false;
}
}
catch (Exception ex) { GlobalHelpers.Trace(ex); }
}

Hide Gridview Using Javascript

I Have some Problem in Hiding Rows of Gridview Using Javascript...
My Js Function is
<script type="text/javascript">
function HideRows(Gdview) {
rows = document.getElementById(Gdview).rows;
for (var i = 0; i < rows.length; i++) {
if (rows[i].cells[0].type == "checkbox") {
if (rows[i].cells[0].childNodes[0].checked) {
rows[i].style.display = "none";
}
}
}
}
</script>
I Have a Gridview ID="Gdview" Which has 5 Columns and Every Column has a checkbox with id="Chk" and i placed a Button after the Gridview(Button id="Btn") i wannt to hide the Selected rows using checkboxes..i tried the following code behind..but it is not working..what wud be the problem?? IS this Wrong Way????
protected void Btn_Click1(object sender, EventArgs e)
{
Btn.Attributes.Add("onclick", "HideRows('" + Gdview + "')");
}
2ND Question Likewise same as first one:
Here i am trying to select and unselect all checkboxes in gridview using respective link buttons...See my markup and JS:
<script type="text/javascript">
function SelectAll(b) {
var grid = document.getElementById("<%= Gdview.ClientID %>");
var cell;
if (grid.rows.length > 0) {
for (var i = 0; i < grid.rows.length; i++) {
cell = grid.rows[i].cells[0];
if (cell.childNodes[0].type == "checkbox")
cell.childNodes[0].checked = b;
}
}
}
</script>
<asp:GridView ID="Gdview" runat="server" AutoGenerateColumns="False"
onrowdatabound="Gdview_RowDataBound">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="Chk" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField HeaderText="SNO" DataField="SerialNo" />
<asp:BoundField HeaderText="Organization" DataField="Organization" />
<asp:BoundField DataField="Origin" HeaderText="Origin"/>
<asp:BoundField DataField="Location" HeaderText="Location" />
<asp:BoundField DataField="Established" HeaderText="Established"/>
<asp:TemplateField>
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:LinkButton ID="lnkChekall" runat="server" Text="Chekall"></asp:LinkButton>
<asp:LinkButton ID="lnkUncheck" runat="server" Text="UnCheckAll"></asp:LinkButton>
and i added Rowdatabound event in codebehind:
protected void Gdview_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
lnkChekall.Attributes.Add("onclick","javascript:SelectAll('" +"true" +"')");
lnkUncheck.Attributes.Add("onclick", "javascript:SelectAll('" + "false" +"')");
}
}
it is not working guys plz help me in my problems with the Javascripts...
EDIT 3
In your second question, I can see there are few problems:
You should not add attribute in RowDataBound. It would add the
attribute for each row instead of only once.
Your javascript is wrong.
You should pass boolean true/false to javascript function, not
string.
To make it work, Add the attributes at Page_Load:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//PopulateGridView
PopulateGrid();
}
lnkChekall.Attributes.Add("onclick", "javascript:SelectAll(true)");
lnkUncheck.Attributes.Add("onclick", "javascript:SelectAll(false )");
}
And change your javascript to this:
<script type="text/javascript">
function SelectAll(b) {
var grid = document.getElementById("<%= Gdview.ClientID %>");
var cell;
if (grid.rows.length > 0) {
for (var i = 0; i < grid.rows.length; i++) {
cell = grid.rows[i].getElementsByTagName("input");
if (cell.length > 0) {
cell[0].checked = b;
}
}
}
}
</script>
You are doing it wrong way! There's no need to call JS from code behind. Just add style to make the row invisible. Here's how I would do it:
In the markup I have my GridView with five check boxes and one row number (Just to populate the Gridview with data). I also have a button :
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:TemplateField HeaderText="CheckBox 1">
<ItemTemplate>
<asp:CheckBox ID="chk1" Text="CheckBox 1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CheckBox 2">
<ItemTemplate>
<asp:CheckBox ID="chk2" Text="CheckBox 2" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CheckBox 3">
<ItemTemplate>
<asp:CheckBox ID="chk3" Text="CheckBox 3" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CheckBox 4">
<ItemTemplate>
<asp:CheckBox ID="chk4" Text="CheckBox 4" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="CheckBox 5">
<ItemTemplate>
<asp:CheckBox ID="chk5" Text="CheckBox 5" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Row">
<ItemTemplate>
<%#Container.DataItem %>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="Btn" runat="server" Text="Button" OnClick="Button1_Click" />
</div>
</form>
</body>
</html>
Now in the code I am populating the GridView with test data. In the button's click event I am looping through all rows of GridView and finding the first CheckBox. If it is checked, I am hiding the row:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//Test Data
var lst = new List<string>() { "Row 1", "Row 2", "Row 3" };
GridView1.DataSource = lst;
GridView1.DataBind();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
var chk = row.FindControl("chk1") as CheckBox;
if (chk != null && chk.Checked)
{
row.Attributes.Add("style", "display:none");
}
}
}
EDIT : If you want to use javascript, still there's no need to assign it from code behind. Add an input to the markup to call js HideRows() function:
<asp:Button ID="Btn" runat="server" Text="Button" OnClick="Button1_Click" />
And the function in the page should look like this:
<script type="text/javascript" >
function HideRows(Gdview) {
var rows = document.getElementById(Gdview).rows;
for( var i=0; i < rows.length; i++ ) {
var inputs = rows[i].getElementsByTagName("input");
if (inputs.length > 0 && inputs[0].checked) {
rows[i].style.display = "none";
}
}
}
</script>
Here's the screenshot before and after clicking the button:
You can download my test project here.
EDIT 2 : If you need to call the function from code behind, just do this:
protected void Button1_Click(object sender, EventArgs e)
{
//Your other code goes here
//
Page.ClientScript.RegisterStartupScript(GetType(), "HideRows", "HideRows('" + GridView1.ClientID + "');", true);
}
client Id of server control is different from the Id you assigned, so try:
document.getElementById("<%= Gdview .ClientID %>")
complete code:
//dont pass as parameter
function HideRows() {
rows = document.getElementById("<%= Gdview.ClientID %>").rows;
for (var i = 0; i < rows.length; i++) {
if (rows[i].cells[0].type == "checkbox") {
if (rows[i].cells[0].childNodes[0].checked) {
rows[i].style.display = "none";
}
}
}
}

Button in templatefield won't fire up Click function

I have a gridview, which gets info by parametrized sqldatasource. I want to fire up a function by pressing a button, sending one of the fields (id).
But function won't even fire up..
here's my aspx part:
<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:igroup20_test2ConnectionString %>"
SelectCommand="select mie.e_num, mie.id, m.f_name, m.l_name from memberInEvent mie, member m where e_num=#num and mie.id=m.id" >
<SelectParameters>
<asp:Parameter DefaultValue="066643776" Name="num" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
<asp:PlaceHolder ID="head_line_ph" runat="server"></asp:PlaceHolder>
<br /><br />
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="false" CssClass="tableStatic">
<Columns>
<asp:TemplateField HeaderText="הסר מאירוע">
<ItemTemplate>
<asp:Button ID="delete_mem" CommandArgument='<%# Bind("id") %>' runat="server" Text="הסר מאירוע" OnClick="remove_member" CssClass="btn btn-primary" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ReadOnly="True" HeaderText="ת.ז"
InsertVisible="False" DataField="id"
SortExpression="ת.ז">
</asp:BoundField>
<asp:BoundField ReadOnly="True" HeaderText="שם פרטי"
InsertVisible="False" DataField="f_name"
SortExpression="שם פרטי">
</asp:BoundField>
<asp:BoundField ReadOnly="True" HeaderText="שם משפחה"
InsertVisible="False" DataField="l_name"
SortExpression="שם משפחה">
</asp:BoundField>
</Columns>
</asp:GridView>
here's my code behind:
protected void Page_Load(object sender, EventArgs e)
{
string e_num = Request.QueryString["enum"];
Label headline_lbl = new Label();
headline_lbl.Text = db.return_event_name(e_num);
headline_lbl.CssClass = "head_line";
head_line_ph.Controls.Add(headline_lbl);
SqlDataSource2.SelectParameters["num"].DefaultValue = e_num;
GridView1.DataSourceID = "SqlDataSource2";
GridView1.DataBind();
if (!IsPostBack)
{
List<string[]> ids_list = db.return_ids_for_event(Convert.ToInt32(e_num));
foreach (string[] s in ids_list)
{
DropDownList1.Items.Add(new ListItem(s[0], s[1]));
}
}
}
protected void remove_member(object sender, EventArgs e)
{
string mem_id = ((Button)sender).CommandArgument;
db.remove_member(mem_id, num);
Response.Redirect("memberInevents.aspx?enum=" + num);
}
EDIT:
after reading Suhani Mody's answer I changed it to fire on the gridview's rowcommand like that: (but still doesn't fire up)
<asp:GridView ID="GridView1" OnRowCommand="GridView1_RowCommand" runat="server" DataSourceID="SqlDataSource1"
AutoGenerateColumns="false" CssClass="tableStatic">
<Columns>
<asp:TemplateField HeaderText="הסר מאירוע">
<ItemTemplate>
<asp:Button ID="delete_mem" CommandArgument='<%# Bind("id") %>' CommandName="MyRowButton" runat="server" Text="הסר מאירוע" CssClass="btn btn-primary" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField ReadOnly="True" HeaderText="ת.ז"
InsertVisible="False" DataField="id"
SortExpression="ת.ז">
</asp:BoundField>
<asp:BoundField ReadOnly="True" HeaderText="שם פרטי"
InsertVisible="False" DataField="f_name"
SortExpression="שם פרטי">
</asp:BoundField>
<asp:BoundField ReadOnly="True" HeaderText="שם משפחה"
InsertVisible="False" DataField="l_name"
SortExpression="שם משפחה">
</asp:BoundField>
</Columns>
</asp:GridView>
cs:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "MyRowButton")
{
string mem_id = e.CommandArgument.ToString();
db.remove_member(mem_id, num);
Response.Redirect("memberInevents.aspx?enum=" + num);
}
}
Put the All code of page load in IsPostBack Block.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string e_num = Request.QueryString["enum"];
Label headline_lbl = new Label();
headline_lbl.Text = db.return_event_name(e_num);
headline_lbl.CssClass = "head_line";
head_line_ph.Controls.Add(headline_lbl);
SqlDataSource2.SelectParameters["num"].DefaultValue = e_num;
GridView1.DataSourceID = "SqlDataSource2";
GridView1.DataBind();
List<string[]> ids_list = db.return_ids_for_event(Convert.ToInt32(e_num));
foreach (string[] s in ids_list)
{
DropDownList1.Items.Add(new ListItem(s[0], s[1]));
}
}
}
If your control (button) is inside a row of a gridview,its event will not fire like how it does for normal buttons. This is called event bubbling. If your controls are inside a container, they become a child of that container.
e.g. in your case, button is a child for gridview and in that case, child cannot fire their events directly. They will send their event to their container/parent i.e. gridview in your case and you need to deal with an event of that parent i.e. gridview.
Try to use OnRowCommand event of your gridview. That should help. You can use "FindControl" method to find your button control on that row.
Hope this helps! Let me know if you need further help.
I think this is your button
<ItemTemplate>
<asp:Button ID="delete_mem" CommandArgument='<%# Bind("id") %>' runat="server" Text="הסר מאירוע" OnClick="remove_member" CssClass="btn btn-primary" />
</ItemTemplate>
Change it to :
<ItemTemplate>
<asp:Button ID="delete_mem" CommandArgument='<%# Eval("id") %>' runat="server" Text="הסר מאירוע" CommandName="remove_member" CssClass="btn btn-primary" />
</ItemTemplate>
Now in gridviews rowcomand event
protectected void Gv_RowCommand(object sender, GridRowCommandEventArgs e)
{
if(e.CommandName.Equals("remove_member"))
{
string mem_id = e.CommandArgument.ToString();
db.remove_member(mem_id, num);
}
System.Thread.Sleep(500); // To hold the current thread for few second to complete the operation and then redirect to your desired page
Response.Redirect("memberInevents.aspx?enum=" + num);
}
See Here
Your old code.
SqlDataSource2.SelectParameters["num"].DefaultValue = e_num;
GridView1.DataSourceID = "SqlDataSource2";
GridView1.DataBind();
if (!IsPostBack)
{
List<string[]> ids_list = db.return_ids_for_event(Convert.ToInt32(e_num));
foreach (string[] s in ids_list)
{
DropDownList1.Items.Add(new ListItem(s[0], s[1]));
}
}
New Code:
SqlDataSource2.SelectParameters["num"].DefaultValue = e_num;
if (!IsPostBack)
{
GridView1.DataSourceID = "SqlDataSource2";
GridView1.DataBind();
List<string[]> ids_list = db.return_ids_for_event(Convert.ToInt32(e_num));
foreach (string[] s in ids_list)
{
DropDownList1.Items.Add(new ListItem(s[0], s[1]));
}
}
Problem:
Binding must be inside !Ispostback

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