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
}
}
Related
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;
I have a listview that I used an update panel in it and all codes is in update panel. I used a check box and an event for it that checks if checkbox is checked the textbox visibility should be true and dropdown list visibility should be false. but after checking checkbox the software break and show Object reference not set to an instance of an object. error. my asp.net codes:
<EditItemTemplate>
<asp:UpdatePanel ID="upchk" runat="server" UpdateMode="Conditional">
<ContentTemplate>
///
<td><asp:Label ID="label17" CssClass="fasele" runat="server" Text="رشته : ">
</asp:Label></td>
<td><asp:DropDownList ID="DropDownList2" DataSourceID="SqlDataSource1"
DataTextField="reshte" DataValueField="reshteId" AutoPostBack="True"
runat="server" ></asp:DropDownList></td>
<td>
<asp:TextBox ID="TextBox8" runat="server"></asp:TextBox>
<asp:CheckBox ID="CheckBox1" runat="server"
oncheckedchanged="CheckBox1_CheckedChanged" AutoPostBack="true"
EnableViewState="true" /> : افزودن رشته جدید</td>
/////
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger EventName="checkedchanged" ControlID="CheckBox1" />
</Triggers>
</asp:UpdatePanel>
</EditItemTemplate>
my .cs codes:
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)ListView1.FindControl("CheckBox1");
TextBox txtrshte = (TextBox)ListView1.FindControl("TextBox8");
DropDownList drpreshte = (DropDownList)ListView1.FindControl("DropDownList2");
if (chk.Checked)
{
txtrshte.Visible = true;
drpreshte.Visible = false;
}
}
In your case, you can find the parent UpdatePanel of the check box and find controls inside it like below:
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
CheckBox chk = (CheckBox)sender;
TextBox txtrshte = (TextBox)chk.Parent.FindControl("TextBox8");
DropDownList drpreshte = (DropDownList)chk.Parent.FindControl("DropDownList2");
if (chk.Checked)
{
txtrshte.Visible = true;
drpreshte.Visible = false;
}
}
EDIT:
I can see that your table structure has serious issue. You can't extend a table through anUpdatePanel this way. You have to move the update panel inside parent tables <td> and create a new table inside the UpdatePanel. Otherwise you will end up messing the rendered html, with doubled controls etc. Your corrected markup should look like this:
<EditItemTemplate>
<tr><td colspan="3">
<asp:UpdatePanel ID="upchk" runat="server" UpdateMode="Conditional">
<ContentTemplate>
///
<table><tr>
<td><asp:Label ID="label17" CssClass="fasele" runat="server" Text="رشته : ">
</asp:Label></td>
<td><asp:DropDownList ID="DropDownList2" DataSourceID="SqlDataSource1"
DataTextField="reshte" DataValueField="reshteId" AutoPostBack="True"
runat="server" ></asp:DropDownList></td>
<td>
<asp:TextBox ID="TextBox8" runat="server"></asp:TextBox>
<asp:CheckBox ID="CheckBox1" runat="server"
oncheckedchanged="CheckBox1_CheckedChanged" AutoPostBack="true"
EnableViewState="true" /> : افزودن رشته جدید</td>
</tr></table>
/////
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger EventName="checkedchanged" ControlID="CheckBox1" />
</Triggers>
</asp:UpdatePanel>
</td></tr>
</EditItemTemplate>
As it turns out, FindControl only searches at the parent control level.
What you need is a recursive findcontrol method that will find your child control:
public static Control FindControlRecursive(this Control control, string id)
{
if (control == null)
{
throw new ArgumentNullException("control")
}
foreach (Control childControl in control.Controls)
{
if (childControl.ID == id)
{
return childControl;
}
Control child = FindControlRecursive(ctl, id);
if (child != null)
{
return child;
}
}
return null;
Hope that helps!
I'm using SQLDependency to catch changes in my database.
http://code.msdn.microsoft.com/How-to-use-SqlDependency-5c0da0b3
This code really works. When I'm changing something in table, event is fired.
private void RefreshWithSqlDependency()
{
iquery = from order in context.Order
where order.Client.Nickname==nickName && order.StatusId!=5
select new { Id = order.Id, Description = order.Description, OrderStatus = order.Status.Name };
notification = new ImmediateNotificationRegister<Order>(context, iquery);
notification.OnChanged += NotificationOnChanged;
}
protected void NotificationOnChanged(object sender, EventArgs e)
{
BindOrderDataList(); //this is executed
}
In BindOrderDataList I'm setting datasource of my datalist.
private void BindOrderDataList()
{
DataListOrders.DataSource = context.Order.Where(x => x.Client.Nickname == nickName && x.StatusId != 5)
.Select(x => new { Id = x.Id, Description = x.Description, OrderStatus = x.Status.Name }).ToList();
DataListOrders.DataBind();
}
Of course nothing happened. Then I put Datalist inside UpdatePanel.
<asp:UpdatePanel ID="UpdatePanelOrdersList" runat="server" UpdateMode="Conditional" OnLoad="UpdatePanelOrdersList_Load">
<ContentTemplate>
<asp:DataList ID="DataListOrders" runat="server" RepeatDirection="Horizontal" RepeatColumns="5" OnItemDataBound="DataListOrders_ItemDataBound"
CellPadding="5" Width="100%" OnItemCommand="DataListOrders_ItemCommand" EnableViewState="False">
<ItemStyle Wrap="True" HorizontalAlign="Center" VerticalAlign="Top"></ItemStyle>
<ItemTemplate>
<asp:Panel ID="Order" runat="server">
<div style="padding: 3px; border: 3px solid; border-color: #F0F0F0">
<h4>Order
<asp:Label ID="OrderId" runat="server" Text='<%# Eval("Id") %>'></asp:Label></h4>
<h5>Desc:
<asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>'></asp:Label></h5>
<h5>Status:
<asp:Label ID="OrderStatus" runat="server" Text='<%# Eval("OrderStatus") %>'></asp:Label></h5>
<br />
<asp:DataList ID="DataListOrderProducts" runat="server" RepeatDirection="Vertical" RepeatColumns="1"
OnItemDataBound="DataListOrderProducts_ItemDataBound" OnItemCommand="DataListOrderProducts_ItemCommand"
EnableViewState="False">
<ItemStyle Wrap="True"></ItemStyle>
<ItemTemplate>
<asp:Panel ID="OrderItem" runat="server">
<h6>Product:
<asp:Label ID="OrderProductId" runat="server" Text='<%# Eval("LineId") %>' CssClass="hiddencol"></asp:Label></h6>
<h6>Product:
<asp:Label ID="Product" runat="server" Text='<%# Eval("ProductName") %>'></asp:Label></h6>
<h6>Status:
<asp:Label ID="ProductStatus" runat="server" Text='<%# Eval("ProductStatus") %>'></asp:Label></h6>
<asp:LinkButton ID="ItemSubmit" runat="server" CommandName="ItemCompleted" Text="Complete" Visible="False" />
</asp:Panel>
</ItemTemplate>
</asp:DataList>
<asp:LinkButton ID="OrderSubmit" runat="server" CommandName="OrderCompleted" Text="Complete" Visible="false" />
</div>
</asp:Panel>
</ItemTemplate>
</asp:DataList>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="NotificationOnChanged" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="DataListOrders" EventName="DataBinding" />
<asp:AsyncPostBackTrigger ControlID="DataListOrders" />
<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />
</Triggers>
</asp:UpdatePanel>
When I'm clicking this Button1 same method as in RefreshWithSqlDependency is executed (NotificationOnChanged) and this is working...
Is there any event that would force UpdatePanel to update when content in DataList changes?
I already tried delegate to raise update event in UpdatePanel...
protected void NotificationOnChanged(object sender, EventArgs e)
{
BindOrderDataList();
LongTimeTask_Delegate d = new LongTimeTask_Delegate(LongTimeTask);
IAsyncResult r = d.BeginInvoke("String", new AsyncCallback(TaskCompleted), null);
d.EndInvoke(r);
}
public delegate void LongTimeTask_Delegate(string str);
public void LongTimeTask(string str)
{
Thread.Sleep(50);
}
public void TaskCompleted(IAsyncResult r)
{
UpdatePanelOrdersList.Update();
}
but no success...
SQLDependency's events can't update updatepanel's content. You have to trigger update event with other event triggers like timer. if timer ticks then updatepanel updates contents. put your update datalist code into timer event. I'm using like that and it works.
You can trying to use timer control.
Here is the sample: http://www.dotnetheaven.com/article/auto-refresh-data-on-page-using-ajax-in-vb.net
Hope this help.
I"m using DataList. in my FooterTemplate I add a radio button I I want check it. but it always return false.
This is my code
<asp:DataList ID="dlDelivery" OnItemDataBound="dlDelivery_DataBound" RepeatColumns="1" RepeatDirection="Vertical" Width="300" runat="server">
<ItemTemplate>
<asp:RadioButton ID="rdoDel" GroupName="aaa" OnCheckedChanged="rdoOther_Changed" AutoPostBack="true" runat="server" />
<asp:Label ID="lblDel1" Text='<%# Eval("Street") %>' runat="server" /><br />
<asp:Label ID="lblDel2" Text='<%# Eval("Suburb") %>' runat="server" />
<span class="clear" />
</ItemTemplate>
<FooterTemplate>
<asp:RadioButton ID="rdoOther" Text="Other" OnCheckedChanged="rdoOther_Changed" AutoPostBack="true" GroupName="aaa" runat="server" />
a
<br class="clear" />
</FooterTemplate>
</asp:DataList>
I check the rdoOther check like this
RadioButton rdoOther = (RadioButton)dlDelivery.Controls[dlDelivery.Controls.Count - 1].Controls[0].FindControl("rdoOther");
if (rdoOther.Checked = true ) // this always fales
{
}
How to fix it?
Try this
foreach (DataListItem item in dlDelivery.Items)
{
if (item.ItemType == ListItemType.Footer)
{
RadioButton rdoOther = (RadioButton)item.FindControl("rdoOther");
}
}
Simply search the radio button in e.Item:
protected void dlDelivery_DataBound(object sender, DataListItemEventArgs e)
{
RadioButton rdoOther = e.Item.FindControl("rdoOther") as RadioButton;
//rdoOther will be null if ListItemType is not footer.
if (rdoOther !=null && rdoOther.Checked)
{
// Do your tasks
}
}
I''ve been working at this for a good while now. I'm simply trying to access something that is in a datalist. I can get items just fine from the PageLoad, even set some dynamic items.. but I can't acess controls from my button click handler.
I've tried other variations such as
ListView1.FindControl("DropDownList1") as DropDownList;
Which gives a NULL.
I've tried
<asp:LinkButton id="addPro" runat="server" CommandArgument='<%# DropDownList1.SelectedItem.Text %>' onCommand ="addPro_Click">Add To Cart</asp:LinkButton>
Which says it can't find the data control in scope.
<asp:ListView ID="ListView1" runat="server"
DataKeyNames="Expr7,Expr1,productNo" DataSourceID="SqlDataSource1">
<AlternatingItemTemplate>
<span style="">
<asp:Label ID="productNameLabel" runat="server"
Text='<%# Eval("productName") %>' />
<br />
<asp:Image runat="server" height = "300" ImageUrl='<%# Eval("img") %>'></asp:Image>
<br />
Description:<br />
<asp:Label ID="itemNotesLabel" runat="server" Text='<%# Eval("itemNotes") %>' />
<br />
stock:
<asp:Label ID="stockLabel" runat="server" Text='<%# Eval("stock") %>' />
<br />
price:
<asp:Label ID="priceLabel" runat="server" Text='<%# "$"+ Eval("price")+".00" %>' />
<br />
Quantitiy: <asp:DropDownList id="DropDownList1" runat="server"> </asp:DropDownList>
<br />
<asp:LinkButton id="addPro" runat="server" CommandArgument='<%# Eval("productNo") %>' onCommand ="addPro_Click">Add To Cart</asp:LinkButton>
<br /><br /><br />
<br /></span>
</AlternatingItemTemplate>
On click
protected void addPro_Click(Object sender, CommandEventArgs e)
{
string addr = "";
string v = Request.QueryString["cat"];
if (v != null)
{
v = "cat=" + v+"&";
}
else
{
v = "";
}
DropDownList stockDD = (DropDownList) FindControl("DropDownList1");
if (stockDD != null)
addr = "~/product.aspx/?" + v + "add=" + e.CommandArgument.ToString() + "&quant=" + stockDD.SelectedItem.Text;
else
addr = "ERROR!";
Response.Redirect(addr+e.CommandArgument.ToString());
ListView1.ItemDataBound += (sa, ea) =>
{
DropDownList stockD = ea.Item.FindControl("DropDownList1") as DropDownList;
Label l = ea.Item.FindControl("Lable12") as Label;
l.Text = stockD.SelectedItem.Text;
addr = "~/product.aspx/?" + v + "add=" + e.CommandArgument.ToString() + "&quant=" + stockD.SelectedItem;
};
// Response.Redirect(addr);
}
Any help in the right direction will help a ton! Thanks!
Try this:
LinkButton lbSender = (LinkButton)sender;
ListViewDataItem lvItem = (ListViewDataItem)(lbSender.Parent);
DropDownList DropDownList1 = lvItem.FindControl("DropDownList1");
ListView.Items is a collection of ListViewDataItem which inherits ListViewItem, which inherits from Control. This means you can find any control in its Controls collection using FindControl. You just have to look at the heirarchy.
Docs for ListView: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.aspx
Docs for ListViewDataItem: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listviewdataitem.aspx
Docs for ListViewItem: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listviewitem.aspx
Docs for Control: http://msdn.microsoft.com/en-us/library/system.web.ui.control.aspx