BottomPagerRow is null - c#

I’m using code behind from Microsoft’s FormView.BottomPagerRow Property article. I’m getting error Object reference not set to an instance of an object on Label pageNum = (Label)pagerRow.Cells[0].FindControl("PageNumberLabel");
How do I display the pager template when there is only one record on the page?
protected void fvWriteUp_DataBound(object sender, EventArgs e)
{
int totalPages = fvWriteUp.PageCount;
int itemCount = fvWriteUp.DataItemCount;
// Get the pager row. From MS FormView.BottomPagerRow Property
FormViewRow pagerRow = fvWriteUp.BottomPagerRow;
// Get the Label controls that display the current page information from the pager row.
Label pageNum =
(Label)pagerRow.Cells[0].FindControl("PageNumberLabel");
Label totalNum =
(Label)pagerRow.Cells[0].FindControl("TotalPagesLabel");
if ((pageNum != null) && (totalNum != null))
{
// Update the Label controls with the current page values.
int page = fvWriteUp.PageIndex + 1;
int count = fvWriteUp.PageCount;
pageNum.Text = page.ToString();
totalNum.Text = count.ToString();
}
}
<PagerTemplate>
<asp:Table CssClass="fvFooter" ID="RecordNav" runat="server">
<asp:TableRow
ID="TableRow4"
runat="server">
<asp:TableCell CssClass="recNav">
<asp:Button ID="btnFirst" CssClass="btn btnRecNav" CommandName="Page" CommandArgument="First" Text="First" runat="server" />
<asp:Button ID="btnPrevious" CssClass="btn btnRecNav" CommandName="Page" CommandArgument="Prev" Text="Previous" runat="server" />
<asp:Button ID="btnNext" CssClass="btn btnRecNav" CommandName="Page" CommandArgument="Next" Text="Next" runat="server" />
<asp:Button ID="btnLast" CssClass="btn btnRecNav" CommandName="Page" CommandArgument="Last" Text="Last" runat="server" />
</asp:TableCell><asp:TableCell CssClass="recCounter">
<asp:Label CssClass="lblRecs" ID="lblRecs1" runat="server" Text="Record"></asp:Label>
<asp:Label CssClass="lblRecCount" ID="PageNumberLabel" runat="server"></asp:Label>
<asp:Label CssClass="lblRecs" ID="lblRecs2" runat="server" Text="of"></asp:Label>
<asp:Label CssClass="lblRecCount" ID="TotalPagesLabel" runat="server"></asp:Label>
</asp:TableCell><asp:TableCell></asp:TableCell></asp:TableRow></asp:Table>
</PagerTemplate>
<PagerSettings FirstPageText="First" LastPageText="Last" Mode="NextPreviousFirstLast" NextPageText="Next" PreviousPageText="Previous" Position="Bottom" />
I’ve tried code like this in PreRender without luck
protected void fvWriteUp_PreRender(object sender, EventArgs e)
{
FormViewRow pagerRow = fvWriteUp.BottomPagerRow;
if (pagerRow != null && pagerRow.Visible == false)
{
pagerRow.Visible = true;
fvWriteUp.BottomPagerRow.Visible = true;
}
}

You might want to check for null on BottomPagerRow property for when there's no data populating your grid.
if (myGridView.BottomPagerRow == null)
return;

Related

Disable image button on Pager Template in c#

I work in ASP.NET c# and MySQL database.
In my gridView I have added this code pagination.
<PagerTemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="/Images/bot_back_1.gif"
CommandArgument="First" CommandName="Page" Visible="true" />
<asp:ImageButton ID="ImageButton2" runat="server" ImageUrl="/Images/bot_back.gif"
CommandArgument="Prev" CommandName="Page" Visible="true" />
Page
<asp:DropDownList ID="ddlPages" runat="server" AutoPostBack="True" CssClass="ddl_Class"
OnSelectedIndexChanged="ddlPages_SelectedIndexChanged" Visible="true">
</asp:DropDownList>
of
<asp:Label ID="lblPageCount" runat="server"></asp:Label>
<asp:ImageButton ID="ImageButton3" runat="server" ImageUrl="/Images/bot_next.gif"
CommandArgument="Next" CommandName="Page" Visible="true" />
<asp:ImageButton ID="ImageButton4" runat="server" ImageUrl="/Images/bot_next_1.gif"
CommandArgument="Last" CommandName="Page" Visible="true" />
</PagerTemplate>
</asp:GridView>
<asp:ImageButton ID="btnAdd" runat="server" Visible="true" OnClick="btnAdd_Click" ImageUrl="/Images/Add_button.gif" />
Now I need to set as visible false all the content on PagerTemplate when is activate :
protected void btnAdd_Click(object sender, ImageClickEventArgs e)
{
gvProducts.ShowFooter = true;
btnAdd.Visible = false;
BindData();
}
I have tried with :
protected void btnAdd_Click(object sender, ImageClickEventArgs e)
{
gvProducts.ShowFooter = true;
btnAdd.Visible = false;
ImageButton1.Visible = false;
BindData();
}
But I have error :
CS0103: The name 'ImageButton1' does not exist in the current context.
Can you please help me figure out the problem?
Thanks in advance.
you have to use the method FindControl() to determine the Control
ImageButton btn = (ImageButton)gvProducts.BottomPagerRow.FindControl("ImageButton1");
btn.Visible = false;

how to get new values from controls at row updating in asp.net 4.0

I have small problem with row updating. I'm working with editable grid view now, at row updating I have faced an issue, I'm not getting new values from controls. I am searching this problem on all sites and I found this article.
However I set this things to my row updating :
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
...........
Session["StartAlpha"] = "All";
Session["GroupByENTYPE"] = -1;
Session["ColumnName"] = null;
Session["SearchtText"] = null;
this.FillGrid((String)Session["StartAlpha"] ?? null, (int)Session["GroupByENTYPE"], (String)Session["ColumnName"] ?? null, (String)Session["SearchText"] ?? null);
}
}
protected void GV_ViewCustomers_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
GridViewRow row = GV_ViewCustomers.Rows[e.RowIndex];
int customerid = Convert.ToInt32(GV_ViewCustomers.DataKeys[e.RowIndex].Value.ToString());
if (!string.IsNullOrEmpty(e.NewValues["Name"].ToString()) && !e.NewValues["type_id"].ToString().Equals("-1"))
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
string owname = null, ownmono = null, room = null, build = null, road = null, area = null, city = null, mobile = null, phone = null, email = null, cpname = null, cpmono = null, remark = null;
bool? UserOFC = null, UserVAT = null, UserINV = null, UserNone = null;
int? country_id = null, state_id = null;
if (!string.IsNullOrEmpty(e.NewValues["Ownername"].ToString().Trim()))
{
owname = e.NewValues["Ownername"].ToString().Trim();
}
if (!string.IsNullOrEmpty(e.NewValues["Ownermob"].ToString().Trim()))
{
ownmono = e.NewValues["Ownermob"].ToString().Trim();
}
if (!string.IsNullOrEmpty(e.NewValues["ContactPerson"].ToString().Trim()))
{
cpname = e.NewValues["ContactPerson"].ToString().Trim();
}
if (!string.IsNullOrEmpty(e.NewValues["ContactPersonmob"].ToString().Trim()))
{
cpmono = e.NewValues["ContactPersonmob"].ToString().Trim();
}
if (!string.IsNullOrEmpty(e.NewValues["Phone"].ToString().Trim()))
{
phone = e.NewValues["Phone"].ToString().Trim();
}
if (!string.IsNullOrEmpty(e.NewValues["Mobile"].ToString().Trim()))
{
mobile = e.NewValues["Mobile"].ToString().Trim();
}
if (!string.IsNullOrEmpty(e.NewValues["Room"].ToString().Trim()))
{
room = e.NewValues["Room"].ToString().Trim();
}
if (!string.IsNullOrEmpty(e.NewValues["Build"].ToString().Trim()))
{
build = e.NewValues["Build"].ToString().Trim();
}
if (!string.IsNullOrEmpty(e.NewValues["Road"].ToString().Trim()))
{
road = e.NewValues["Road"].ToString().Trim();
}
if (!string.IsNullOrEmpty(e.NewValues["Area"].ToString().Trim()))
{
area = e.NewValues["Area"].ToString().Trim();
}
if (!string.IsNullOrEmpty(e.NewValues["City"].ToString().Trim()))
{
city = e.NewValues["City"].ToString().Trim();
}
if (!e.NewValues["country_id"].ToString().Equals("-1"))
{
country_id = int.Parse(e.NewValues["country_id"].ToString());
}
if (!e.NewValues["state_id"].ToString().Equals("-1"))
{
state_id = int.Parse(e.NewValues["state_id"].ToString());
}
if (!string.IsNullOrEmpty(e.NewValues["Email"].ToString().Trim()))
{
email = e.NewValues["Email"].ToString().Trim();
}
if (!string.IsNullOrEmpty(e.NewValues["Remark"].ToString().Trim()))
{
remark = e.NewValues["Remark"].ToString().Trim();
}
UserOFC = bool.Parse(e.NewValues["UserOFC"].ToString());
UserVAT = bool.Parse(e.NewValues["UserVAT"].ToString());
UserINV = bool.Parse(e.NewValues["UserINV"].ToString());
UserNone = bool.Parse(e.NewValues["UserNone"].ToString());
db.UpdateParty(e.NewValues["Name"].ToString().Trim(), int.Parse(e.NewValues["type_id"].ToString()), owname, ownmono, room, build, road, area, city, phone, mobile, email, cpname, cpmono, UserOFC, UserVAT, UserINV, UserNone, state_id, country_id, remark, db.Users.Where(u => u.Username.Equals((String)Session["Username"])).Select(u => u.Ref_no).FirstOrDefault(), customerid);
db.SubmitChanges();
GV_ViewCustomers.EditIndex = -1;
this.FillGrid((String)Session["StartAlpha"] ?? null, (int)Session["GroupByENTYPE"], (String)Session["ColumnName"] ?? null, (String)Session["SearchText"] ?? null);
UpdatePanel10.Update();
MPE.Show();
}
}
}
protected void GV_ViewCustomers_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Edit)
{
using (DataClassesDataContext db = new DataClassesDataContext())
{
DropDownList dl = (DropDownList)e.Row.FindControl("DDL_Types1");
dl.DataSource = db.PartyTypes.Select(t => t).ToList();
dl.DataBind();
dl.SelectedValue = DataBinder.Eval(e.Row.DataItem, "type_id").ToString();
DropDownList dl1 = (DropDownList)e.Row.FindControl("DDL_CountryNames1");
dl1.DataSource = db.Countries.Select(c => c).ToList();
dl1.DataBind();
if (!string.IsNullOrEmpty(DataBinder.Eval(e.Row.DataItem, "country_id").ToString()))
{
dl1.SelectedValue = DataBinder.Eval(e.Row.DataItem, "country_id").ToString();
DropDownList dl2 = (DropDownList)e.Row.FindControl("DDL_StateNames1");
dl2.DataSource = db.States.Where(s => s.country_id.Equals(int.Parse(DataBinder.Eval(e.Row.DataItem, "country_id").ToString()))).Select(s => s).ToList();
dl2.DataBind();
}
DataRowView rowView1 = (DataRowView)e.Row.DataItem;
if (rowView1["UserOFC"] != null)
{
(e.Row.FindControl("chk_UserOFC1") as CheckBox).Checked = Convert.ToBoolean(e.Row.DataItem.Equals("UserOFC").ToString());
}
if (rowView1["UserVAT"] != null)
{
(e.Row.FindControl("chk_UserVAT1") as CheckBox).Checked = Convert.ToBoolean(e.Row.DataItem.Equals("UserVAT").ToString());
}
if (rowView1["UserINV"] != null)
{
(e.Row.FindControl("chk_UserINV1") as CheckBox).Checked = Convert.ToBoolean(e.Row.DataItem.Equals("UserINV").ToString());
}
if (rowView1["UserNone"] != null)
{
(e.Row.FindControl("chk_UserNone1") as CheckBox).Checked = Convert.ToBoolean(e.Row.DataItem.Equals("UserNone").ToString());
}
}
}
}
Updated
this is my second grid view aspx markup :
<asp:UpdatePanel ID="UpdatePanel18" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="GV_ViewReasons" runat="server" AllowPaging="True"
AllowSorting="True" AutoGenerateColumns="False" CellPadding="4" ShowFooter="True"
GridLines="None" Width="100%"
DataKeyNames="Id" onrowcommand="GV_ViewReasons_RowCommand" onrowdatabound="GV_ViewReasons_RowDataBound"
onsorting="GV_ViewReasons_Sorting"
ondatabound="GV_ViewReasons_DataBound"
onpageindexchanging="GV_ViewReasons_PageIndexChanging"
onprerender="GV_ViewReasons_PreRender"
onrowediting="GV_ViewReasons_RowEditing"
onrowupdating="GV_ViewReasons_RowUpdating"
onrowcancelingedit="GV_ViewReasons_RowCancelingEdit"
onrowdeleting="GV_ViewReasons_RowDeleting" HorizontalAlign="Left">
<RowStyle CssClass="grid" HorizontalAlign="Left" />
<Columns>
<asp:TemplateField>
<EditItemTemplate>
<asp:ImageButton ID="imgbtnUpdate" CommandName="Update" runat="server" ImageUrl="../images/1366376844_001_06.gif" ToolTip="Update" Height="20px" Width="20px" ValidationGroup="EditCharge" CausesValidation="false"/>
<asp:ImageButton ID="imgbtnCancel" runat="server" CommandName="Cancel" ImageUrl="../images/1366376484_001_05.png" ToolTip="Cancel" Height="20px" Width="20px" />
</EditItemTemplate>
<FooterTemplate>
<asp:ImageButton ID="imgbtnAdd" runat="server" ImageUrl="../images/1398687211_plus-sign.png"
CommandName="AddNew" Width="24px" Height="24px" ToolTip="Add new reason"
ValidationGroup="AddNewReason" CausesValidation="false"/>
</FooterTemplate>
<ItemTemplate>
<table>
<tr>
<td><asp:ImageButton ID="imgbtnEdit" CommandName="Edit" runat="server" ImageUrl="../images/1366376599_001_45.png" ToolTip="Edit" Height="20px" Width="20px" /></td>
<td><asp:ImageButton ID="imgbtnDelete" CommandName="Delete" Text="Edit" runat="server" ImageUrl="../images/1366377028_Cancel.png" ToolTip="Delete" Height="20px" Width="20px" /></td>
</tr>
</table>
</ItemTemplate>
<HeaderStyle CssClass="headinglist_bg" HorizontalAlign="Left" />
<ItemStyle HorizontalAlign="Left" />
</asp:TemplateField>
<asp:TemplateField HeaderText="Reason" SortExpression="ReasonText">
<HeaderStyle CssClass="headinglist_bg" HorizontalAlign="Left" />
<ItemTemplate>
<asp:LinkButton ID="lbut_reason" runat="server"
CommandArgument='<%# Eval("Id") %>' CommandName="Select"
Text='<%# Eval("ReasonText").ToString().Length > 50 ? Eval("ReasonText").ToString().Substring(0,50)+"...":Eval("ReasonText") %>'
ToolTip='<%# Bind("ReasonText") %>'></asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="txt_reason1" runat="server" CssClass="input"
ValidationGroup="UpdateReason" Text='<%# Eval("ReasonText") %>'></asp:TextBox>
<ajaxToolkit:TextBoxWatermarkExtender ID="txt_reason1_TextBoxWatermarkExtender"
runat="server" Enabled="True" TargetControlID="txt_reason1"
WatermarkText="Enter reson text">
</ajaxToolkit:TextBoxWatermarkExtender>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="txt_reason1" Display="None"
ErrorMessage="Reason text is required" SetFocusOnError="True"
ValidationGroup="UpdateReason"></asp:RequiredFieldValidator>
<ajaxToolkit:ValidatorCalloutExtender ID="ValidatorCalloutExtender12"
runat="server" CloseImageUrl="~/images/close.gif"
TargetControlID="RequiredFieldValidator2"
WarningIconImageUrl="~/images/Warning.gif">
</ajaxToolkit:ValidatorCalloutExtender>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txt_reason" runat="server" CssClass="input"
ValidationGroup="AddNewReason"></asp:TextBox>
<ajaxToolkit:FilteredTextBoxExtender ID="txt_reason_FilteredTextBoxExtender"
runat="server" Enabled="True"
FilterType="Custom, UppercaseLetters, LowercaseLetters"
TargetControlID="txt_reason" ValidChars=" ,.">
</ajaxToolkit:FilteredTextBoxExtender>
<ajaxToolkit:TextBoxWatermarkExtender ID="txt_reason_TextBoxWatermarkExtender"
runat="server" Enabled="True" TargetControlID="txt_reason"
WatermarkText="Enter reson text">
</ajaxToolkit:TextBoxWatermarkExtender>
<asp:RequiredFieldValidator
ID="RequiredFieldValidator1"
runat="server"
ErrorMessage="Reason text is required"
ControlToValidate="txt_reason"
ValidationGroup="AddNewReason"
Display="None" SetFocusOnError="True"></asp:RequiredFieldValidator>
<ajaxToolkit:ValidatorCalloutExtender ID="ValidatorCalloutExtender12" runat="server" TargetControlID="RequiredFieldValidator1" WarningIconImageUrl="~/images/Warning.gif" CloseImageUrl="~/images/close.gif" >
</ajaxToolkit:ValidatorCalloutExtender>
</FooterTemplate>
<HeaderTemplate>
<asp:LinkButton ID="lbut_sortreason" runat="server"
CommandArgument="ReasonText" CommandName="Sort" CssClass="normaltext"
Font-Bold="true" Text="Reason"></asp:LinkButton>
<asp:PlaceHolder ID="placeholderreason" runat="server"></asp:PlaceHolder>
</HeaderTemplate>
<ItemStyle CssClass="quicklink" HorizontalAlign="Left" />
</asp:TemplateField>
</Columns>
<EmptyDataRowStyle BorderWidth="0px" Width="0px" HorizontalAlign="Left"/>
<EmptyDataTemplate>
<asp:Label ID="Label2" runat="server" ForeColor="Red"
Text="No Records are found"></asp:Label>
</EmptyDataTemplate>
<PagerStyle CssClass="pager" HorizontalAlign="Left" VerticalAlign="Middle" />
<PagerTemplate>
<table>
<tr>
<td>
<asp:ImageButton ID="ImageButton5" runat="server"
AlternateText="Go to First Page" CommandArgument="First" CommandName="Page"
ImageUrl="../images/1330128819_resultset_first.png" />
</td>
<td>
<asp:ImageButton ID="ImageButton6" runat="server" AlternateText="Previous Page"
CommandArgument="Prev" CommandName="Page"
ImageUrl="../images/1330128981_resultset_previous.png" />
</td>
<td>
Page <asp:DropDownList ID="ddlPages1" runat="server" AutoPostBack="True"
Width="50px" onselectedindexchanged="ddlPages1_SelectedIndexChanged">
</asp:DropDownList>
of
<asp:Label ID="lblPageCount1" runat="server"></asp:Label>
</td>
<td>
<asp:ImageButton ID="ImageButton7" runat="server" AlternateText="Next Page"
CommandArgument="Next" CommandName="Page"
ImageUrl="../images/Farm-Fresh_resultset_next.png" />
</td>
<td>
<asp:ImageButton ID="ImageButton9" runat="server"
AlternateText="Go to Last Page" CommandArgument="Last" CommandName="Page"
ImageUrl="../images/1330128876_resultset_last.png" />
</td>
</tr>
</table>
</PagerTemplate>
<FooterStyle CssClass="pager" VerticalAlign="Bottom" />
</asp:GridView>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="GV_ViewReasons" EventName="RowCommand"/>
<asp:AsyncPostBackTrigger ControlID="GV_ViewReasons" EventName="RowUpdating" />
<asp:AsyncPostBackTrigger ControlID="GV_ViewReasons" EventName="RowDeleting" />
</Triggers>
</asp:UpdatePanel>

Get value from gridview footer in tab control

I've got a tab control with a gridview in it. I want to add new records using the footer row but when I try and save the record, I can't find the value in the textbox. I've set the clientidmode = static, I've also tried using a recursive findcontrol but to no avail. Please can someone help
Thanks
<asp:UpdatePanel ID="pnl" runat="server" ChildrenAsTriggers="true">
<ContentTemplate>
<asp:TabContainer ID="TabDetails" runat="server" AutoPostBack="true" OnActiveTabChanged="TabDetails_ActiveTabChanged"
ActiveTabIndex="1">
<asp:TabPanel runat="server" ID="TabNotes" HeaderText="Notes" CssClass="tabinactive">
<ContentTemplate>
<asp:GridView ID="GrdNotes" ClientIDMode="Static" runat="server" AutoGenerateColumns="false"
Width="99%" OnRowEditing="GrdNotes_RowEditing" OnRowCancelingEdit="GrdNotes_RowCancelingEdit"
OnRowUpdating="GrdNotes_RowUpdating" OnRowDeleting="GrdNotes_RowDeleting" OnRowCreated="GrdNotes_RowCreated"
ShowFooter="false">
<Columns>
<asp:TemplateField HeaderText="Notes">
<ItemTemplate>
<asp:HiddenField ID="hfNotesID" runat="server" Value='<%# Bind("Notes_ID")%>' />
<asp:Label ID="LblNotes" runat="server" Text='<%# Bind("Notes")%>'></asp:Label>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox ID="TxtNotes" runat="server" Text='<%# Bind("Notes")%>'></asp:TextBox>
</EditItemTemplate>
<FooterTemplate>
<asp:TextBox ID="TxtNewNotes" ClientIDMode="Static" runat="server" Width="300px"></asp:TextBox>
</FooterTemplate>
</asp:TemplateField>
<asp:BoundField DataField="Notes_Date" ReadOnly="True" DataFormatString="{0:dd/MM/yyyy}"
HeaderText="Date" />
<asp:BoundField DataField="FullName" ReadOnly="True" HeaderText="Entered By" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnAdd" runat="server" Text="Add Notes" OnClick="btnAddVisitNotes_Click" />
</ContentTemplate>
</asp:TabPanel>
</asp:TabContainer>
</ContentTemplate>
</asp:UpdatePanel>
private void BindNotes(int id)
{
var qry = from vn in dc.sp_list_notes(id)
orderby vn.Notes_Date descending
select vn;
GrdNotes.DataSource = qry.ToList();
GrdNotes.DataBind();
}
protected void GrdNotes_RowCreated(Object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
var lnk = new LinkButton();
lnk.Text = "Save";
lnk.ID = "btnAddNotesSave";
lnk.CausesValidation = false;
lnk.Command += new CommandEventHandler(btnAddNotesSave_Click);
lnk.CssClass = "norm";
e.Row.Cells[1].Controls.Add(lnk);
var lbl = new Label();
lbl.Text = "XX";
lbl.ID = "LblSpace";
lbl.CssClass = "norm_w";
e.Row.Cells[1].Controls.Add(lbl);
var lnk1 = new LinkButton();
lnk1.Text = "Cancel";
lnk1.ID = "btnAddNotesCancel";
lnk1.CausesValidation = false;
lnk1.Command += new CommandEventHandler(btnAddNotesCancel_Click);
lnk1.CssClass = "norm";
e.Row.Cells[1].Controls.Add(lnk1);
}
protected void btnAddNotes_Click(object sender, EventArgs e)
{
GrdNotes.ShowFooter = true;
BindNotes(int.Parse(hfID.Value));
}
protected void btnAddNotesSave_Click(object sender, EventArgs e)
{
TextBox txt = (TextBox)GrdNotes.FooterRow.FindControl("TxtNewNotes") ;
string sNotes = txt.Text;
}
"Can't find the value in the textbox" means that you can find the TextBox via FindControl but it's Text property returns String.Empty?
There is definitely text in the textbox, but it's returning "". if I
do a check txt.id it returns "TxtNewNotes" but txt.text = ""
Maybe you have forgotten to add a !IsPostBack check before you call BindNotes in Page_Load.
Thank you, yes I can't believe I forgot that!
Even the most experienced ASP.NET developers sometimes forget this ;)
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
BindNotes();
}

How to bind repeater ItemDataBound, to update on dropdownlist SelectedIndexChanged

Im a rookie on ASP.Net and been stuck for this for a while.
Everytime the index of my dropdown changes i want to fill my repeater with objects.
This works fine, but when im selecting a value in my dropdown that dosent contain any objects the old objects from the last call is still there, i want them to disappear.
I've tried to clear the items from the repeater using Datasource=null and then do a Databind again, but that dosent work.
I think it has with the ItemDataBound event on my repeater.
The ItemDatabound is not called when i select a value in the dropsdownlist that dosent contain any objects.
ItemDataBound CODE:
protected void rptStudentQuestion_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
Label lblAnswer = e.Item.FindControl("lblAnswer") as Label;
TextBox tbxAnswer = e.Item.FindControl("tbxAnswer") as TextBox;
Button btnSend = e.Item.FindControl("btnSend") as Button;
if (lblAnswer.Text == "" || lblAnswer == null)
{
lblAnswer.Visible = false;
lblAnswer.Enabled = false;
tbxAnswer.Visible = true;
tbxAnswer.Enabled = true;
btnSend.Enabled = true;
btnSend.Visible = true;
}
else
{
lblAnswer.Visible = true;
lblAnswer.Enabled = true;
tbxAnswer.Visible = false;
tbxAnswer.Enabled = false;
btnSend.Enabled = false;
btnSend.Visible = false;
}
}
}
OnSelectedIndexChanged CODE:
protected void DrpdwnLectureName_SelectedIndexChanged(object sender, EventArgs e)
{
string SelectedLecture = DrpdwnLectureName.SelectedValue;
string user = Server.HtmlEncode(Context.User.Identity.Name).ToString();
using (var client = new WCFReference.SRSServiceClient())
{
var LectureList = client.GetTeacherLecture(user);
foreach (var item in LectureList)
{
if (item.LectureName == DrpdwnLectureName.SelectedValue)
{
var list = client.GetStudentQuestions(item.LectureID, user);
rptStudentQuestion.DataSource = list;
rptStudentQuestion.DataBind();
}
}
}
}
Markup CODE:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:DropDownList ID="DrpdwnLectureName" AutoPostBack="True" runat="server" OnSelectedIndexChanged="DrpdwnLectureName_SelectedIndexChanged"></asp:DropDownList>
<asp:Panel ID="PrintPanel" runat="server">
<asp:Label ID="Label1" runat="server" Text="Gör en .pdf på besvarade frågor"></asp:Label>
<asp:Button ID="btnDoPdf" runat="server" Text="Button" OnClick="btnDoPdf_Click" />
</asp:Panel>
<asp:Repeater ID="rptStudentQuestion" runat="server" OnItemCommand="rptStudentQuestion_ItemCommand" OnItemDataBound="rptStudentQuestion_ItemDataBound">
<ItemTemplate>
<asp:Label ID="lblQuestion" runat="server" Text='<%# Eval("StudentQuestionQuestion") %>'></asp:Label>
<br />
<asp:TextBox ID="tbxAnswer" runat="server" Visible="false"></asp:TextBox>
<asp:Button ID="btnSend" CommandName="SendAnswer" runat="server" Text="Skicka svar" CommandArgument='<%# Eval("StudentQuestionID") %>' />
<br />
<asp:Label ID="lblAnswer" runat="server" Text='<%# Eval("StudentQuestionAnswer") %>' Visible="false"></asp:Label>
<br />
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
</asp:UpdatePanel>
Updated Code as Requested(Snippet from DrpdwnLectureName_SelectedIndexChanged)
if (item.LectureName == DrpdwnLectureName.SelectedValue)
{
var list = client.GetStudentQuestions(item.LectureID, user);
if (list.Count() > 0)
{
rptStudentQuestion.Visible = true;
rptStudentQuestion.DataSource = list;
rptStudentQuestion.DataBind();
}
else
{
rptStudentQuestion.Visible = false; // In debug it preforms this, but nothing happens.
}
}
This is not a solution, but can solve your update panel updating problem. You can control updatepanel update manually doing this:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="false">
<ContentTemplate>
<asp:DropDownList ID="DrpdwnLectureName" AutoPostBack="True" runat="server" OnSelectedIndexChanged="DrpdwnLectureName_SelectedIndexChanged"></asp:DropDownList>
<asp:Panel ID="PrintPanel" runat="server">
<asp:Label ID="Label1" runat="server" Text="Gör en .pdf på besvarade frågor"></asp:Label>
<asp:Button ID="btnDoPdf" runat="server" Text="Button" OnClick="btnDoPdf_Click" />
</asp:Panel>
<asp:Repeater ID="rptStudentQuestion" runat="server" OnItemCommand="rptStudentQuestion_ItemCommand" OnItemDataBound="rptStudentQuestion_ItemDataBound">
<ItemTemplate>
<asp:Label ID="lblQuestion" runat="server" Text='<%# Eval("StudentQuestionQuestion") %>'></asp:Label>
<br />
<asp:TextBox ID="tbxAnswer" runat="server" Visible="false"></asp:TextBox>
<asp:Button ID="btnSend" CommandName="SendAnswer" runat="server" Text="Skicka svar" CommandArgument='<%# Eval("StudentQuestionID") %>' />
<br />
<asp:Label ID="lblAnswer" runat="server" Text='<%# Eval("StudentQuestionAnswer") %>' Visible="false"></asp:Label>
<br />
</ItemTemplate>
</asp:Repeater>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DrpdwnLectureName" />
</Triggers>
</asp:UpdatePanel>
and when you want to update the panel in code, you call: "UpdatePanel1.Update()"
if (item.LectureName == DrpdwnLectureName.SelectedValue)
{
var list = client.GetStudentQuestions(item.LectureID, user);
if (list.Count() > 0)
{
rptStudentQuestion.Visible = true;
rptStudentQuestion.DataSource = list;
rptStudentQuestion.DataBind();
}
else
{
rptStudentQuestion.Visible = false; // In debug it preforms this, but nothing happens.
UpdatePanel1.Update() //This 'force' updatepanel updating
}
}

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

Categories

Resources