Repeater list is not getting updated in OnItemCommand method - c#

I have a repeater control. In OnItemCommand method of repeater, after doing some operations I am trying to refresh the repeater list so that it could show me the updated list. But somehow repeater list is not updated in method. However when I reload the page then repeater list gets updated with most recent items.
ASPX:
<asp:Label ID="Message1" runat="server" ForeColor="Blue" Text=""></asp:Label>
<div id="ListingAgentsData" class="panel panel-default" style="width: 920px;">
<asp:Repeater ID="rptagentList" runat="server" OnItemCommand="rptagentList_OnItemCommand">
<HeaderTemplate>
<table id="results1" cellpadding="4" cellspacing="1" width="100%">
<tr>
<td>
<strong>AgentID</strong>
</td>
<td>
<strong>Email</strong>
</td>
<td>
<strong>FullName</strong>
</td>
<td>
<strong>Driver License/Passport</strong>
</td>
<td>
<strong>Action</strong>
</td>
</tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td>
<asp:Label ID="lblDayofweek" runat="server" Text='<%#Eval("AgentID")%>'></asp:Label>
</td>
<td>
<asp:Label ID="lblTime" runat="server" Text='<%#Eval("Email")%>'></asp:Label>
</td>
<td>
<asp:Label ID="lblCharges" runat="server" Text='<%#Eval("FullName")%>'></asp:Label>
</td>
<td>
<asp:Label ID="Label1" runat="server" Text='<%#Eval("DriverLicense")%>'></asp:Label>
</td>
<td>
<asp:LinkButton ID="ibtn" runat="server" Text="Approve" CommandName="Approve" CommandArgument='<%#Eval("AgentID")%>' />
<asp:LinkButton ID="LinkButton1" runat="server" Text="Reject" CommandName="Reject" CommandArgument='<%#Eval("AgentID")%>' />
</td>
</tr>
</ItemTemplate>
<FooterTemplate>
</table>
</FooterTemplate>
</asp:Repeater>
.CS:
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Username"] == null)
Response.Redirect("../Login/Default.aspx");
else
{
Init();
}
}
protected void rptagentList_OnItemCommand(object source, RepeaterCommandEventArgs e)
{
try
{
if (e.CommandName == "Approve")
{
int agentId = Convert.ToInt32(e.CommandArgument);
GM gm = new GM();
if (gm.ApproveListingAgent(agentId))
{
Message1.Text = "Listing Agent with ID:"+agentId+" is approved!";
Init();
}
}
else if (e.CommandName == "Reject")
{
}
}
catch (Exception ex)
{
throw ex;
}
}
private void Init()
{
ListingAgent Agent = new ListingAgent();
DataTable dt = Agent.getPendingListingAgents();
if (dt.Rows.Count > 0)
{
rptagentList.DataSource = dt;
rptagentList.DataBind();
}
}
What am I missing?
Please help!

Related

Deleting item from ListView

I am trying to do an ASP.NET application. I am using a DataSet which I set as DataSource in a ListView that I have in my .aspx file. The problem is when I click the delete button nothing seems to happen, but when I refresh the browser I get an error message as follows:
"To display the webpage again, the web browser needs to resend the
information you've previosly submitted."
I have really tried to figure out what I am doing wrong or what might cause this. This is my C# code:
namespace WebApplication1
{
public partial class _Default : Page
{
DataSet orderDetails;
protected void Page_Load(object sender, EventArgs e)
{
Message.Text = "";
string orderPath = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/orders.xml";
string orderSchemaPath = AppDomain.CurrentDomain.BaseDirectory + "/App_Data/orderschema.xsd";
XDocument document = XDocument.Load(orderPath);
XmlSchemaSet schemas = new XmlSchemaSet();
schemas.Add("", XmlReader.Create(orderSchemaPath));
bool errors = false;
document.Validate(schemas, (o, err) =>
{
System.Diagnostics.Debug.WriteLine("Validation error: {0}", err.Message);
errors = true;
});
if (!errors)
{
System.Diagnostics.Debug.WriteLine("XML document successfully validated.");
try
{
orderDetails = new DataSet();
orderDetails.ReadXml(orderPath);
listViewOrders.DataSource = orderDetails;
listViewOrders.DataBind();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error: " + ex);
}
}
else
{
System.Diagnostics.Debug.WriteLine("XML document does not validate.");
}
System.Diagnostics.Debug.WriteLine("Page_load done");
}
void BindData()
{
listViewOrders.DataSource = orderDetails;
listViewOrders.DataBind();
}
//Call databind method in your prerender event
protected void Page_PreRender(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void OrderListView_ItemCommand(object sender, ListViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
listViewOrders.DeleteItem(e.Item.DataItemIndex);
BindData();
}
}
protected void OrdersListView_ItemDeleted(object sender, ListViewDeletedEventArgs e)
{
//Check if an exception occurred to display an error message.
if (e.Exception != null)
{
Message.Text = "An exception occurred deleting the contact.";
e.ExceptionHandled = true;
}
else
{
// Clear the selected index.
listViewOrders.SelectedIndex = -1;
}
}
protected void OrdersListView_OnItemDeleting(object sender, ListViewDeleteEventArgs e)
{
}
}
}
And this is the ListView that I have in my .aspx file:
<asp:ListView ID="listViewOrders"
DataKeyNames="orderid"
runat="server"
OnItemDeleting="OrdersListView_OnItemDeleting"
OnItemCommand="OrderListView_ItemCommand">
<LayoutTemplate>
<table cellpadding="2" width="640px" border="1" runat="server" id="tblProducts">
<tr runat="server">
<th runat="server">Order person</th>
<th runat="server">Order ID</th>
<th runat="server">Delete</th>
</tr>
<tr runat="server" id="itemPlaceholder" />
</table>
</LayoutTemplate>
<ItemTemplate>
<tr runat="server">
<td>
<asp:Label ID="FirstNameLabel" runat="Server" Text='<%#Eval("orderperson") %>' />
</td>
<td valign="top">
<asp:Label ID="LastNameLabel" runat="Server" Text='<%#Eval("orderid") %>' />
</td>
<td>
<asp:LinkButton ID="DeleteButton" runat="Server" class="glyphicon glyphicon-remove" CommandName="Delete" CommandArgument="X" />
</td>
</tr>
</ItemTemplate>
<EditItemTemplate>
<tr style="background-color: #ADD8E6">
<td>
<asp:LinkButton ID="UpdateButton" runat="server" CommandName="Update" Text="Update" />
<asp:LinkButton ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" />
</td>
<td>
<asp:TextBox ID="FirstNameTextBox" runat="server" Text='<%#Bind("orderperson") %>'
MaxLength="50" /><br />
</td>
<td>
<asp:TextBox ID="LastNameTextBox" runat="server" Text='<%#Bind("orderid") %>'
MaxLength="50" /><br />
</td>
</tr>
</EditItemTemplate>
</asp:ListView>
When you are using the listView Commands you have to update the panels.
Place your listView inside a asp:panel like this
<asp:UpdatePanel ID="UpdatePanel1" UpdateMode="Conditional" runat="server">
<ContentTemplate>
... your list View Code
</ContentTemplate>
</asp:UpdatePanel>
And after the DataBind you have to update the panel by
UpdatePanel1.Update();

How to capture button click event from asp.net DataList

I have a DataList control in asp.net webform, inside this DataLIst I have 2 labels that are bound to database, and one button.
One of the label represent Id and other one Stock.
I want to capture the button click event of specific product, and then add that product to the user cart.
Here is my datalist:
<asp:DataList ID="dListProduct" runat="server" RepeatColumns="4" OnItemCommand="dListProduct_ItemCommand">
<ItemTemplate>
<div>
<table class="table-responsive" border="1">
<tr>
<td>
<asp:Label runat="server" Text="Available Stock: " ></asp:Label><asp:Label ID="Label1" runat="server" Text='<%# Eval("Stock")%>'></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label runat="server" Text="Id" ></asp:Label><asp:Label ID="lblPId" runat="server" Text='<%# Eval("Product_Id")%>' Visible="false"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Button id="btnAddtoCart" runat="server" Text="Add to Cart"/>
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:DataList>
Here is the code I am using in OnItemCommand Event of DataList:
protected void dListProduct_ItemCommand(object source, DataListCommandEventArgs e)
{
Label lbl = (Label)e.Item.FindControl("lblPId");
Response.Write(lbl.Text);
}
but this code never get executed.
Can anyone help me out?
Copy and paste the code below exactly the way I have it.
Code behind:
public partial class DataListExample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
this.BindData();
}
}
private void BindData()
{
MyStock stock1 = new MyStock { Product_Id = 1, Stock = "Stock 1" };
MyStock stock2 = new MyStock { Product_Id = 2, Stock = "Stock 2" };
dListProduct.DataSource = new List<MyStock> { stock1, stock2 };
dListProduct.DataBind();
}
protected void dListProduct_ItemCommand(object source, DataListCommandEventArgs e)
{
Label lbl = (Label)e.Item.FindControl("lblPId");
Response.Write(lbl.Text);
}
}
public class MyStock
{
public int Product_Id { get; set; }
public string Stock { get; set; }
}
.ASPX:
<asp:DataList ID="dListProduct" runat="server" RepeatColumns="4" OnItemCommand="dListProduct_ItemCommand">
<ItemTemplate>
<div>
<table class="table-responsive" border="1">
<tr>
<td>
<asp:Label runat="server" Text="Available Stock: "></asp:Label><asp:Label ID="Label1" runat="server" Text='<%# Eval("Stock")%>'></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label runat="server" Text="Id"></asp:Label><asp:Label ID="lblPId" runat="server" Text='<%# Eval("Product_Id")%>' Visible="false"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnAddtoCart" runat="server" Text="Add to Cart" />
</td>
</tr>
</table>
</div>
</ItemTemplate>
</asp:DataList>

Checkbox state not changed on postback

I have the following mark up for a User Control (.ascx)
<table>
<tr>
<td>
<asp:Label ID="Label1" runat="server" Text="Select Logical Symbol to Search:"></asp:Label>
</td>
<td>
<asp:DropDownList ID="ddlComponentType" runat="server"
onselectedindexchanged="ddlComponentType_SelectedIndexChanged" AutoPostBack="true">
</asp:DropDownList>
</td>
<td>
<asp:CheckBox ID="chkAdvSearchAllLibs" runat="server" ToolTip="Check this box to search all available libraries" Text="Search All Libraries"/>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Label2" runat="server" Text="Search by Logical Symbol Properties:"></asp:Label>
</td>
<td>
</td>
</tr>
On page Load
protected void Page_Load(object sender, EventArgs e)
{
SearchResults(ref attributeSearch, compTypeID);
}
where SearchResults is
private void SearchResults(ref string attributeSearch, int compTypeID)
{
DataTable dtResults = this.AdvancedSearchControl.GetSearchResults(ref attributeSearch, compTypeID);
}
And in my UserControl.ascx.cs
public DataTable GetSearchResults(ref string _attrVals, int compTypeID)
{
//Other Logic Goes Here
IEnumerable<Model.ComponentInfo.ComponentType> compTypeResult = from compTypes in BLLibrary.GetComponentTypeBasedOnLib(this.CurrentLibraryId, this.CurrentLibrary, this.chkAdvSearchAllLibs.Checked) select compTypes.Value;
}
this.chkAdvSearchAllLibs.Checked is always false no matter if the check-box is checked on page and posted back or not.
Server side:
Add AutoPostBack="True" to the CheckBox. It's not posting back.
Client side:
<asp:CheckBox runat="server" ID="cb" onclick="checkboxchanged(this);" />
function checkboxchanged( sender ) {
if ( sender.checked ) {
// clicked and checked
} else {
// clicked and unchecked
}
}

Value of boolean cell in gridview to shown in a radio button

I have a Boolea(bit) value in database and i shown it in Grid View in the cell no. 2 like this
MyGrdView.SelectedRow.Cells[2] // for any row selected this cell have a boolean value 0 or 1
The GridView in a View 1 in Multiview control
I need in another View (view2), i can shown this value in check box, so if the boolean cell in gridview have 0, the check box checked and for 1 the check box unchecked
ASP Code:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:MultiView ID="LocationsMultiView" runat="server" ActiveViewIndex="0">
<asp:View ID="View1" runat="server">
<div>
<div class="EU_TableScroll" id="showData" style="display: block">
<table class="auto-style1">
<tr>
<td>
<asp:Button ID="Btn_ShowReminders" runat="server" Text="Show Reminders" OnClick="Btn_ShowReminders_Click" />
<asp:Button ID="Btn_EditReminder" runat="server" Text="Edit Reminder" Enabled="False" OnClick="Btn_EditReminder_Click" />
<asp:Button ID="Btn_RemoveReminder" runat="server" Enabled="False" OnClick="Btn_RemoveReminder_Click" Text="Delete Reminder" />
</td>
</tr>
<tr>
<td>
<asp:Label ID="Lbl_Error" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:GridView ID="Grd_Reminders" runat="server" CssClass="EU_DataTable" GridLines="Horizontal" OnSelectedIndexChanged="Grd_Reminders_SelectedIndexChanged">
<Columns>
<asp:ButtonField ButtonType="Button" CommandName="Select" HeaderText="Select" ShowHeader="True" Text=">>>" />
</Columns>
</asp:GridView>
</td>
</tr>
<tr>
<td>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl="~/img/ajax-loader.gif" />
</ProgressTemplate>
</asp:UpdateProgress>
</td>
</tr>
</table>
</div>
</div>
</asp:View>
<asp:View ID="View2" runat="server">
<table class="auto-style1">
<tr>
<td colspan="3">
<asp:Label ID="Lbl_EditRemTitle" runat="server" Text="Edit Reminder"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Lbl_Edit_Title" runat="server" Text="Title"></asp:Label>
</td>
<td>
<asp:TextBox ID="Txt_EditTitle" runat="server"></asp:TextBox>
</td>
<td>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator" ValidationGroup="g1" ControlToValidate="Txt_EditTitle">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
<asp:Label ID="Lbl_Edit_Content" runat="server" Text="Content"></asp:Label>
</td>
<td>
<asp:TextBox ID="Txt_Edit_Content" runat="server"></asp:TextBox>
</td>
<td> </td>
</tr>
<tr>
<td class="auto-style2">
<asp:Label ID="Lbl_Edit_Desc" runat="server" Text="Description"></asp:Label>
</td>
<td class="auto-style2">
<asp:TextBox ID="Txt_Edit_Description" runat="server" TextMode="MultiLine"></asp:TextBox>
</td>
<td class="auto-style2"> </td>
</tr>
<tr>
<td>
<asp:Label ID="Lbl_Edit_TurnOn" runat="server" Text="Turn On"></asp:Label>
</td>
<td>
<asp:CheckBox ID="CheckBox1" runat="server" />
</td>
<td> </td>
</tr>
<tr>
<td>
<asp:Label ID="Lbl_Edit_Alw" runat="server" Text="Always"></asp:Label>
</td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>
<asp:Label ID="Lbl_Edit_Public" runat="server" Text="Public"></asp:Label>
</td>
<td> </td>
<td> </td>
</tr>
<tr>
<td>
<asp:Label ID="Lbl_Edit_Radius" runat="server" Text="Radius"></asp:Label>
</td>
<td> </td>
<td> </td>
</tr>
<tr>
<td colspan="3">
<asp:Label ID="Lbl_Edit_Msg" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td>
<asp:UpdateProgress ID="UpdateProgress2" runat="server">
</asp:UpdateProgress>
</td>
</tr>
<tr>
<td colspan="3">
<asp:Button ID="Button1" runat="server" Text="Save" ValidationGroup="g1" />
<asp:Button ID="Btn_Cancel_Edit" runat="server" OnClick="Btn_Cancel_Edit_Click" Text="Cancel" />
</td>
</tr>
</table>
</asp:View>
</asp:MultiView>
</ContentTemplate>
CS Code:
public partial class webusercontrols_remindersctl : System.Web.UI.UserControl
{
Locations Lo = new Locations();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Utilities.ReadFromCookie("logincookie", "user", Request) != null)
{
UserInfo UI = new UserInfo();
string userNameOnWB = Request.Cookies["logincookie"]["user"];
}
}
// Btn_ShowReminders_Click(null, null);
}
protected void Grd_Reminders_SelectedIndexChanged(object sender, EventArgs e)
{
Btn_RemoveReminder.Enabled = true;
Grd_Reminders.SelectedRow.BackColor = Color.FromName("#E56E94");
Btn_RemoveReminder.Enabled = true;
Btn_EditReminder.Enabled = true;
}
protected void Btn_ShowReminders_Click(object sender, EventArgs e)
{
Locations loc = new Locations();
string UserName = Request.Cookies["logincookie"]["user"];
Grd_Reminders.DataSource = loc.GetRemindersForUser(UserName);
Grd_Reminders.DataBind();
Grd_Reminders.SelectedIndex = -1;
Btn_RemoveReminder.Enabled = false;
Btn_EditReminder.Enabled = false;
Lbl_Error.Text = String.Empty;
}
protected void Btn_RemoveReminder_Click(object sender, EventArgs e)
{
int ID = Int32.Parse((Grd_Reminders.SelectedRow.Cells[1].Text).ToString());
if (Lo.RemoveLocations(ID))
{
Lbl_Error.Text = "Reminder Removed!";
}
else
{
Lbl_Error.Text = "Error Removing Reminder!";
}
Btn_RemoveReminder.Enabled = false;
Grd_Reminders.DataBind();
}
protected void Btn_EditReminder_Click(object sender, EventArgs e)
{
LocationsMultiView.ActiveViewIndex = 1;
if (Grd_Reminders.SelectedRow.Cells[5] != null)
Txt_EditTitle.Text = Grd_Reminders.SelectedRow.Cells[5].Text;
if (Grd_Reminders.SelectedRow.Cells[6] != null)
Txt_Edit_Content.Text = Grd_Reminders.SelectedRow.Cells[6].Text;
if (Grd_Reminders.SelectedRow.Cells[7] != null)
Txt_Edit_Description.Text = Grd_Reminders.SelectedRow.Cells[7].Text;
if (Grd_Reminders.SelectedRow.Cells[8] != null)
CheckBox1.Checked = Convert.ToBoolean(Grd_Reminders.SelectedRow.Cells[8]);
}
protected void Btn_Cancel_Edit_Click(object sender, EventArgs e)
{
LocationsMultiView.ActiveViewIndex = 0;
}
}

Not able to access radio button inside datalist in code behind

I am having radio button inside datalist. And I need to access them in code behind. But all my efforts are not working. This is what I am doing :
<asp:DataList ID="dlPaper" runat="server" RepeatColumns="1" RepeatDirection="Vertical"
Width="755px" onitemcommand="item_command">
<ItemTemplate>
<table>
<tr>
<td>
Question :
</td>
<td colspan ="4">
<asp:Label ID="lblQuestion" runat="server" Text='<%#Eval("Question") %>'></asp:Label>?
<asp:Label ID="lblQID" runat="server" Text='<%#Eval("QID") %>' Visible="False"></asp:Label>
</td>
</tr>
<tr>
<td></td>
<td>
A
</td>
<td>
<asp:Label ID="lblOption1" runat="server" Text='<%#Eval("Option1") %>'></asp:Label>
</td>
<td>
B
</td>
<td>
<asp:Label ID="lblOption2" runat="server" Text='<%#Eval("Option2") %>'></asp:Label>
</td>
</tr>
<tr> <td></td>
<td>
C
</td>
<td>
<asp:Label ID="lblOption3" runat="server" Text='<%#Eval("Option3") %>'></asp:Label>
</td>
<td>
D
</td>
<td>
<asp:Label ID="lblOption4" runat="server" Text='<%#Eval("Option4") %>'></asp:Label>
</td>
</tr>
</table>
<table>
<tr>
<td>
Answer :
</td>
<td>
<asp:RadioButton ID="rdOption1" runat="server" Text="A" GroupName="Ans"/>
</td>
<td>
<asp:RadioButton ID="rdOption2" runat="server" Text="B" GroupName="Ans" />
</td>
<td>
<asp:RadioButton ID="rdOption3" runat="server" Text="C" GroupName="Ans" />
</td>
<td>
<asp:RadioButton ID="rdOption4" runat="server" Text="D" GroupName="Ans" />
</td>
<td>
<asp:Button ID="tbnAnswer" runat="server" Text="Submit Answer" CommandName='<%#Eval("QID") %>' OnCommand='item_command'/>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
Code behind it is as :
protected void item_command(object source, CommandEventArgs e)
{
try
{
_ds = new DataSet();
int p = WebHelper.Cast(e.CommandName, 0);
ViewState["QID"] = p;
AnswersBAL abl = new AnswersBAL(SessionContext.SystemUser);
abl.LoadByQID(_ds, p);
if (_ds != null && _ds.Tables[abl.SqlEntityX].Rows.Count > 0)
{
int AID = System.Convert.ToInt32(_ds.Tables[0].Rows[0]["AID"]);
abl.LoadByPrimaryKey(_ds, AID);
screenscrap(_ds.Tables[abl.SqlEntityX].Rows[0]);
abl.Save(_ds);
}
else
{
abl.LoadByPrimaryKey(_ds, int.MinValue);
DataRow dr = _ds.Tables[abl.SqlEntityX].NewRow();
_ds.Tables[abl.SqlEntityX].Rows.Add(dr);
dr["QID"] = System.Convert.ToInt32(ViewState["QID"]);
dr["StdID"] = 1;
//sessioncontext.systemuser
//dr["Option1"]= //
abl.Save(_ds);
}
}
catch (Exception err)
{ }
}
But I am not able to access radio buttons in code behind.
try like this
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "YourCommandName")
{
r1 = (RadioButton)e.Item.FindControl("rdButton");
}
}

Categories

Resources