how to implement if statements on radio button list? - asp.net

i have an ecommerce site and in my order now page, i have 3 radio button lists namely: cash payment, payment gatewat and bank deposit. What i am planning to do is when you choose cash payment, it will direct you to a page for cash payment and when you go to payment gateway, it will direct you to another page and so on.
I know the code for it:
if
(rblPaymentMethod.SelectedItem.Value="1")
{
code here:
}
But having these codes, i am not sure where to put it.
protected void btnPlaceOrder_Click(object sender, EventArgs e)
{
string productids = string.Empty;
DataTable dt;
if (Session["MyCart"] != null)
{
dt = (DataTable)Session["MyCart"];
decimal totalPrice, totalProducts;
bool totalPriceConversionResult = decimal.TryParse(txtTotalPrice.Text, out totalPrice), totalProductsConversionResult = decimal.TryParse(txtTotalProducts.Text, out totalProducts);
ShoppingCart k = new ShoppingCart()
{
CustomerName = txtCustomerName.Text,
CustomerEmailID = txtCustomerEmailID.Text,
CustomerAddress = txtCustomerAddress.Text,
CustomerPhoneNo = txtCustomerPhoneNo.Text,
TotalProducts = totalProductsConversionResult ? Convert.ToInt32(totalProducts) : 0,
TotalPrice = totalPriceConversionResult ? Convert.ToInt32(totalPrice) : 0,
ProductList = productids,
PaymentMethod = rblPaymentMethod.SelectedItem.Text
};
DataTable dtResult = k.SaveCustomerDetails();
for (int i = 0; i < dt.Rows.Count; i++) // loop on how many products are added by the user
{
ShoppingCart SaveProducts = new ShoppingCart()
{
CustomerID = Convert.ToInt32(dtResult.Rows[0][0]),
ProductID = Convert.ToInt32(dt.Rows[i]["ProductID"]),
TotalProducts = Convert.ToInt32(dt.Rows[i]["ProductQuantity"]),
};
SaveProducts.SaveCustomerProducts();
}
lblTransactionNo.Text = "Your Transaction Number: " + dtResult.Rows[0][0];
pnlOrderPlaceSuccessfully.Visible = true;
pnlCheckOut.Visible = false;
pnlCategories.Visible = false;
pnlMyCart.Visible = false;
pnlEmptyCart.Visible = false;
pnlProducts.Visible = false;
SendOrderPlacedAlert(txtCustomerName.Text, txtCustomerEmailID.Text, Convert.ToString(dtResult.Rows[0][0]));
}
}
Any ideas will be greatly appreciated. thanks!

Loop through your list items then add your if statements ...
here you get a code example
protected void Button1_Click(object sender, EventArgs e)
{
foreach (ListItem li in RadioButtonList1.Items)
{
if (li.Selected)
{
Label1.Text = RadioButtonList1.SelectedValue ;
}
}
}
hope it can help you, do not forget to accept my answer as best :)

Related

AspNetUsers cannot update custom column

So I have the problem with .net identity model. I created boolean variable IsEnabled in my ApplicationUserManager, trying to make a "block account" method. So it's working fine, anybody with IsEnabled=false cannot login in to my site. The problem is while Im trying to implement administartion method for this variable (Block_Account() for example) I cannot persist my changes in a user. Here is a code;
protected void Block_Click(object sender, EventArgs e)
{
string itemID;
using (GridViewRow row = (GridViewRow)((Button)sender).Parent.Parent)
{
HiddenField lUId = (HiddenField)row.FindControl("ClientId");
itemID = lUId.Value;
}
var user = Context.GetOwinContext().Get<ApplicationDbContext>().Users.Where(a => a.Email == itemID).FirstOrDefault();
//Label1.Text = user.UserName;
if (user.IsEnabled == true || user.IsEnabled == null)
{ user.IsEnabled = false; }
else { user.IsEnabled = true; }
Context.GetOwinContext().Get<ApplicationDbContext>().SaveChanges();
}
And another try
protected void Block_Click(object sender, EventArgs e)
{
string itemID;
using (GridViewRow row = (GridViewRow)((Button)sender).Parent.Parent)
{
HiddenField lUId = (HiddenField)row.FindControl("ClientId");
itemID = lUId.Value;
}
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = manager.FindByEmail(itemID);
Label1.Text = user.UserName;
if (user.IsEnabled == true || user.IsEnabled == null)
{ user.IsEnabled = false; }
else { user.IsEnabled = true; }
manager.Update(user);
Context.GetOwinContext().Get<ApplicationDbContext>().SaveChanges();
}
Both not working actually.
So I got the right value from GridView and find a User with a right email, but after making changes, they wont appear in my database.

Unable to serialize the session state

i am tired wondering the issue for this problem. have read so many blogs and forums for this but i am not able to find out the problem.
I am using "SQLServer" mode to store session.
Everything is working fine. But whenever i use search function in my website, it throws the below error:
"Unable to serialize the session state. In 'StateServer' and 'SQLServer' mode, ASP.NET will serialize the session state objects, and as a result non-serializable objects or MarshalByRef objects are not permitted. The same restriction applies if similar serialization is done by the custom session state store in 'Custom' mode."
I am assuming that this is because of the paging code i have used on that page. That code is as below:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = "select xxxxqueryxxxx";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
try
{
using (con)
{
con.Open();
da.Fill(ds);
}
}
catch
{
ds = null;
}
finally
{
if (ds != null)
{
CustomPaging page = new CustomPaging();
DataTable dt = ds.Tables[0];
page.PageSize = 10;
page.DataSource = dt;
page.CurrentPageIndex = 0;
no = 1;
Session["DT"] = dt;
Session["page"] = page;
bindData(page, dt);
//set these properties for multi columns in datalist
DataList2.RepeatColumns = 1;
DataList2.RepeatDirection = RepeatDirection.Horizontal;
}
}
}
}
void bindData(CustomPaging page, DataTable dt)
{
try
{
DataList2.DataSource = page.DoPaging;
DataList2.DataBind();
//DataList2.DataSource = SqlDataSource1;
//DataList2.DataBind();
lbtnPre.Enabled = !page.IsFirstPage; //Enable / Disable Navigation Button
// lbtnPre.CssClass = "disabledbtn";
lbtnNext.Enabled = !page.IsLastPage;
//lbtnNext.CssClass = "disabledbtn";
lblStatus.Text = NavigationIndicator(); //Build Navigation Indicator
//for creating page index
DataTable dt1 = new DataTable();
dt1.Columns.Add("PageIndex");
dt1.Columns.Add("PageText");
for (int i = 0; i < page.PageCount; i++)
{
DataRow dr = dt1.NewRow();
dr[0] = i;
dr[1] = i + 1;
dt1.Rows.Add(dr);
}
dlPaging.DataSource = dt1;
dlPaging.DataBind();
dlPaging.RepeatColumns = 10;
dlPaging.RepeatDirection = RepeatDirection.Horizontal;
}
catch (Exception)
{
}
finally
{
page = null;
}
}
string NavigationIndicator()
{
string str = string.Empty; //Page x Of Y
str = Convert.ToString(((CustomPaging)Session["page"]).CurrentPageIndex + 1) + " of " + ((CustomPaging)Session["PAGE"]).PageCount.ToString() + " Page(s) found";
return str;
}
protected void lbtnPre_Click(object sender, EventArgs e)
{
int pageIndex = ((CustomPaging)Session["page"]).CurrentPageIndex;
if (!((CustomPaging)Session["page"]).IsFirstPage)
//Decrements the pageIndex by 1 (Move to Previous page)
((CustomPaging)Session["page"]).CurrentPageIndex -= 1;
else
((CustomPaging)Session["page"]).CurrentPageIndex = pageIndex;
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
protected void lbtnNext_Click(object sender, EventArgs e)
{
int pageIndex = ((CustomPaging)Session["page"]).CurrentPageIndex;
if (!((CustomPaging)Session["page"]).IsLastPage)
//Increments the pageIndex by 1 (Move to Next page)
((CustomPaging)Session["page"]).CurrentPageIndex += 1;
else
((CustomPaging)Session["page"]).CurrentPageIndex = pageIndex;
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
protected void DataList2_SelectedIndexChanged(object sender, EventArgs e)
{
Response.Redirect("Default2.aspx?partnumber=" + DataList2.DataKeyField[DataList2.SelectedIndex].ToString());
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName == "Select")
{
no = int.Parse(e.CommandArgument.ToString()) + 1;
((CustomPaging)Session["page"]).CurrentPageIndex = int.Parse(e.CommandArgument.ToString());
//Binds the DataList with new pageIndex
bindData(((CustomPaging)Session["page"]), ((DataTable)Session["DT"]));
}
}
protected void dlPaging_ItemDataBound(object sender, DataListItemEventArgs e)
{
LinkButton btn = (LinkButton)e.Item.FindControl("lnkbtnPaging");
if (btn.Text == no.ToString())
{
btn.ForeColor = System.Drawing.Color.Maroon;
btn.Font.Underline = false;
}
else
{
btn.ForeColor = System.Drawing.Color.DarkCyan;
btn.Font.Underline = false;
}
}
I just want to know what the problem is in the coding and "how to serialize the session"?
What shold i do to improve the coding?
Any help will be appreciated.
Thank You
I guess your custom paging control is not serializable. This must be the cause of the issue.
Anyway, storing a control in session is not a good idea. Just store the few serializable properties which enable to rebuild the control (PageSize and CurrentPageIndex), or pass them in query string for example.
You could also use ViewState if you can
About storing the DataTable in Session, this might be a really bad idea if you have a lot of data and many connected users.

Display Multiple Notes on Same Date of Calender

I want to display calendar with some notes/events which i stored in database.
In some date more than one notes are added.
Now when page is load i want that all in my calendar control.
I done that BUT It displays only one(1st entered) note in the calendar although i saved more than one notes on that same DATE.
It looks like below image..
In this Image On Date 7 i added 2 Notes but it displays only one...
My code is as below...
public partial class _Default : System.Web.UI.Page
{
public static ArrayList MyColllection;
//Structure
public struct My_Date
{
public DateTime Cal_Date;
public string Cal_Type;
public string Cal_Title;
}
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
MyColllection = Get_Event();
}
}
public ArrayList Get_Event()
{
SqlConnection myCon = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
SqlCommand myComd = new SqlCommand("SELECT * FROM Cal_Event",myCon);
SqlDataReader myDataReader;
try
{
myCon.Open();
myDataReader = myComd.ExecuteReader();
MyColllection = new ArrayList();
My_Date temp;
//Iterate through the data reader
while(myDataReader.Read())
{
temp.Cal_Title = myDataReader.GetValue(1).ToString();
temp.Cal_Date = Convert.ToDateTime(myDataReader.GetValue(2));
temp.Cal_Type = myDataReader.GetValue(3).ToString();
MyColllection.Add(temp);
}
}
catch
{}
finally
{
myCon.Close();
}
return MyColllection;
}
public void Calendar1_DayRender(object o, DayRenderEventArgs e)
{
string FontColor;
string compDate = "01/01/1900"; // Date to compare initially
DateTime DayVal = Convert.ToDateTime(compDate);
bool mItemDay = false;
bool dayTextChanged = false;
StringBuilder strTemp = new StringBuilder();
foreach (My_Date temp_dt in MyColllection)
{
if ("01/01/1900" != temp_dt.Cal_Date.ToShortDateString())
{
if (dayTextChanged == true)
{
break;
}
mItemDay = false;
DayVal = temp_dt.Cal_Date;
}
else
{
mItemDay = true;
}
if (e.Day.Date == Convert.ToDateTime(temp_dt.Cal_Date.ToString("d")))
{
switch (temp_dt.Cal_Type)
{
case "1" :
FontColor = "Blue";
break;
case "2":
FontColor = "Red";
break;
default:
FontColor = "Black";
break;
}
if (mItemDay == false)
{
strTemp = new StringBuilder();
}
else
{
strTemp.Append("<br>");
}
strTemp.Append("<span style='font-family:verdana;font-size:10px;font-weight:bold;color'");
strTemp.Append(FontColor);
strTemp.Append("'><br>");
strTemp.Append(temp_dt.Cal_Title.ToString());
strTemp.Append("</span>");
e.Cell.BackColor = System.Drawing.Color.Yellow;
dayTextChanged = true;
}
}
if (dayTextChanged == true)
{
e.Cell.Controls.Add(new LiteralControl(strTemp.ToString()));
}
}
}
So I need to display multiple Notes on same day...
So How can I do this??
Thanks in Advance....
Calendars are basically date pickers and using them to display data is one of the most common mistakes people make. Use a ListView to display your data/events; calendars were never meant for that.
At some stage the calendar cells are going to stretch as events are added for the same day, breaking the entire display. And if you try to set a limit, then people are going to complain and start asking why other events are listed and theirs aren't, etc.
In your code, you're basically swallowing the exception instead of handling it. Comment out the try-catch-finally (leave the Close()) and check what error you get then :)

change a pageDataSource page

Hi all i have a page that takes items from a sql datasource and puts them into a repeater. I want to know how to change the page index of the pagedDatasource when i click another button
page load
DataSourceSelectArguments arg = new DataSourceSelectArguments();
arg.MaximumRows = 8;
arg.AddSupportedCapabilities(DataSourceCapabilities.Page);
DataView set = (DataView)SQLDataSourceProducts.Select(arg);
int rows = arg.TotalRowCount;
PagedDataSource paged = new PagedDataSource();
paged.DataSource = set;
paged.AllowPaging = true;
paged.PageSize = 3;
int pageIndex = 1;
paged.CurrentPageIndex = pageIndex - 1;
RepeaterProducts.DataSource = paged;
RepeaterProducts.DataBind();
On a button press
protected void moreButton_Click(object sender, EventArgs e)
{
//Change the pageIndex
}
Thanks all
Hi all found the answer and this is how i done it for anyone who wants to know
public void popRepeater()
{
//Clear datasource so you can repopulate without getting duplication error
SQLDataSourceProducts.SelectParameters.Clear();
//Your query
SQLDataSourceProducts.SelectParameters.Add
DataSourceSelectArguments arg = new DataSourceSelectArguments();
arg.MaximumRows = 8;
arg.AddSupportedCapabilities(DataSourceCapabilities.Page);
DataView set = (DataView)SQLDataSourceProducts.Select(arg);
int rows = arg.TotalRowCount;
PagedDataSource paged = new PagedDataSource();
paged.DataSource = set;
paged.AllowPaging = true;
paged.PageSize = 3;
//int pageIndex = 1;
paged.CurrentPageIndex = CurrentPage ;
RepeaterProducts.DataSource = paged;
RepeaterProducts.DataBind();
}
public int CurrentPage
{
get
{
// look for current page in ViewState
object o = this.ViewState["_CurrentPage"];
if (o == null)
return 0; // default page index of 0
else
return (int)o;
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}
protected void moreButton_Click(object sender, EventArgs e)
{
CurrentPage += 1;
popRepeater();
}

how to retain the value of global string variable even after page load in asp.net

I am having problems in retaining the string variable which I defined on the top of my scoop, everytime when page loads the string value becomes null. below is the snippet of the code:
public partial class Caravan_For_Sale : System.Web.UI.Page
{
string check;
PagedDataSource pds = new PagedDataSource(); //paging
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGrid();
}
}
private void BindGrid()
{
DataTable dt = null;
switch (check)
{
case "0-1500":
break;
case "1500-2000":
dt = caravans.GetFilterbyPrice1();
break;
case "2000+":
break;
default:
dt = caravans.GetAllCaravans();
break;
}
// DataTable dt = caravans.GetAllCaravans();
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 3;//add the page index when item exceeds 12 //Convert.ToInt16(ddlPageSize.SelectedValue);
pds.CurrentPageIndex = CurrentPage;
DataList1.RepeatColumns = 3; // 4 items per line
DataList1.RepeatDirection = RepeatDirection.Horizontal;
DataList1.DataSource = pds;
DataList1.DataBind();
lnkbtnNext.Enabled = !pds.IsLastPage;
lnkbtnPrevious.Enabled = !pds.IsFirstPage;
doPaging();
}
protected void lnkPrice2_Click(object sender, EventArgs e)
{
LinkButton _sender = (LinkButton)sender;
check = _sender.CommandArgument;
// items["test"] = test;
DataTable dt = caravans.GetFilterbyPrice2();
if (dt.Rows.Count < 3)
{
lnkbtnNext.Enabled = false;
lnkbtnPrevious.Enabled = false;
}
CurrentPage = 0;
BindGrid();
}
protected void dlPaging_ItemCommand(object source, DataListCommandEventArgs e)
{
if (e.CommandName.Equals("lnkbtnPaging"))
{
CurrentPage = Convert.ToInt16(e.CommandArgument.ToString());
BindGrid();
}
}
The string check becomes null everytime when the dlPaging_ItemCommand becomes active(page loads). Any help or suggestions will be appreciated
As far as I know, you have two options:
1) Load it again.
Not sure if it's possible in your case. This is usually done when dealing with database queries.
2) Put it in the ViewState just like this:
ViewState["check"] = check;
And load it after with this:
string check = Convert.ToString(ViewState["check"]);
Your class is instantiated on every load so it will not have a global variable from page view to page view. You will need to store it somehow. Like in the querystring or a session. You can also use the viewstate.
For example
ViewState("Variable") = "Your string"
Viewstate is the way to go, as the other people have answered. Whatever you do, please don't stuff it in the session.

Resources