In Online Exam,How I Will Show The Next quest and ans After Clicking The Next Button.I Can Show Only The First quest - asp.net

The code I have so far tried
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Time();
Question();
}
}
public void Question()
{
int res2 = Convert.ToInt32(lblsubject.Text);
var res3 = (from test in obj.Quest where test.subid == res2 select test).FirstOrDefault();
if (res3 != null)
{
lblqst.Text = res3.question;
opt1.Text = res3.answ1;
opt2.Text = res3.answ2;
opt3.Text = res3.answ3;
opt4.Text = res3.answ4;
}
}
protected void btn_next_Click(object sender, EventArgs e)
{
/*what code to use here?this is the next button where after clicking it next question will display*/
}

Related

How do I add a variable for the textbox ID inside a function?

public partial class _Default : System.Web.UI.Page
{
double[] array = new double[5];
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
for(int i=0;i<5;i++)
{
array[i] = Convert.ToDouble(TextBox(i+1).Text);
}
}
}
This is my code, I have 5 textboxes, I'd like to refer to them with the int (i) inside the loop.
array[i] = Convert.ToDouble(TextBox(i+1).Text);
the text boxes are named 'TextBox1' , 'TextBox2', 'TextBox3, etc.
Is it possible in C#?
You could if you use Control.FindControl
protected void Button1_Click(object sender, EventArgs e)
{
for (int i = 0; i < 5; i++)
{
TextBox currenTextBox = (TextBox) FindControl("TextBox" + i);
if (!string.IsNullOrEmpty(currenTextBox?.Text))
{
if (double.TryParse(currenTextBox.Text, out var result))
{
array[i] = result;
}
}
}
}

Cant Get Data To Return To My Grid View Using Linq in ASP.NET

Not sure why but i cant get my data to return. It starts out saying there is not data records to display. But when i select the month and year of the information i am looking for the grid view disappears. Any suggestions
NutritionEntities context;
protected void Page_Load(object sender, EventArgs e)
{
context = new NutritionEntities();
if (!IsPostBack)
{
for (int i = DateTime.Now.Year; i > 1988; i--)
{
ddlYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
}
int selectedMonth = int.Parse(ddlMonth.SelectedValue);
int selectedYear = int.Parse(ddlYear.SelectedValue);
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
GridView1.DataBind();
}
}
protected void ddlMonth_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedMonth = int.Parse(ddlMonth.SelectedValue);
int selectedYear = int.Parse(ddlYear.SelectedValue);
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
GridView1.DataBind();
}
protected void ddlYear_SelectedIndexChanged(object sender, EventArgs e)
{
int selectedMonth = int.Parse(ddlMonth.SelectedValue);
int selectedYear = int.Parse(ddlYear.SelectedValue);
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
GridView1.DataBind();
}
you have verify the binding of your control grid, i suggest add only object to the datasource of the grid on the pageLoad when the postback its false like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridView1.DataSource =
from exercise in context.Exercises
where exercise.exerciseDate.Value.Month == selectedMonth && exercise.exerciseDate.Value.Year == selectedYear
select new
{
exercise.exerciseDate,
exercise.duration,
exercise.caloriesBurned,
exercise.averageHR,
exercise.distanceInMiles,
exercise.notes
};
}
GridView1.DataBind();
}
the problem is when you add the objects to datasource , when any event refresh the web page like select the control is unbinding, i hope help you,, see you!!

Listview change applies after 2nd postback?

i have a listview and a button out of this list view, on button click i want to add a "insert" row defined in InsertItemTemplate. The problem is when i click the button, this row is added(i know this because when a do any postback aftewards this row really shows), but isnt shown/rendered. So the question is: why this change doesn´t apply on the first postback - button click? here is my code:
EDIT:
Whole Codebehind:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ListItem ByName = new ListItem("By name", "Name");
ListItem ByPhone = new ListItem("By phone", "Phone");
ListItem ByEmail = new ListItem("By email", "Email");
FilterTypeDDL.Items.Add(ByName);
FilterTypeDDL.Items.Add(ByPhone);
FilterTypeDDL.Items.Add(ByEmail);
FilterTypeDDL.DataBind();
}
}
//protected void ListView_ItemCommand(object sender, ListViewCommandEventArgs e)
//{
//switch (e.CommandName)
//{
//case "EditItem":
// break;
//case "InsertItem":
// if (Page.IsValid)
// {
// string NameTxt = ((TextBox)(ListView.InsertItem.FindControl("NameTextBox"))).Text.Trim();
// string PhoneTxt = ((TextBox)(ListView.InsertItem.FindControl("PhoneTextBox"))).Text.Trim();
// string EmailTxt = ((TextBox)(ListView.InsertItem.FindControl("EmailTextBox"))).Text.Trim();
// DAORestaurant.InsertRestaurant(NameTxt, PhoneTxt, EmailTxt);
// ListView.InsertItemPosition = InsertItemPosition.None;
// ListView.DataSource = DAORestaurant.GetRestaurants();
// ListView.DataBind();
// break;
// }
// break;
//case "CancelCreation":
// ListView.InsertItemPosition = InsertItemPosition.None;
// ListView.DataSource = DAORestaurant.GetRestaurants();
// ListView.DataBind();
// break;
//case "Articles":
// Session["Restaurant"] = e.CommandArgument.ToString();
// Control ArticlesCtrl = LoadControl("~/Controls/Article.ascx");
// ListViewItem Item = (ListViewItem)e.Item;
// Item.FindControl("CtrlPlaceHolder").Controls.Add(ArticlesCtrl);
//}
//}
protected void closeButton_Click(object sender, EventArgs e)
{
}
protected void newArticleButton_Click(object sender, EventArgs e)
{
}
protected void NewRestaurantBtn_Click(object sender, EventArgs e)
{
ListView.InsertItemPosition = InsertItemPosition.LastItem;
//SetDataSource();
//ListView.DataBind();
}
protected void ValidateName(object source, ServerValidateEventArgs args)
{
string NameTxt = ((TextBox)(ListView.InsertItem.FindControl("NameTextBox"))).Text.Trim();
args.IsValid = (NameTxt.Length > 2 && NameTxt.Length < 51);
}
protected void ValidateUniqueness(object source, ServerValidateEventArgs args)
{
string NameTxt = ((TextBox)(ListView.InsertItem.FindControl("NameTextBox"))).Text.Trim();
args.IsValid = DAORestaurant.IsUnique(NameTxt);
}
protected void ValidatePhone(object source, ServerValidateEventArgs args)
{
string PhoneTxt = ((TextBox)(ListView.InsertItem.FindControl("PhoneTextBox"))).Text.Trim();
Regex regex = new Regex(#"^\d{3}\s\d{3}\s\d{3}$");
args.IsValid = regex.IsMatch(PhoneTxt);
}
protected void ValidateEmail(object source, ServerValidateEventArgs args)
{
string EmailTxt = ((TextBox)(ListView.InsertItem.FindControl("EmailTextBox"))).Text.Trim();
Regex regex = new Regex(#"^([\w\.\-]+)#([\w\-]+)((\.(\w){2,3})+)$");
args.IsValid = regex.IsMatch(EmailTxt);
}
protected void ShowAllBtn_Click(object sender, EventArgs e)
{
Session["ALL"] = true;
ListView.DataSource = DAORestaurant.GetRestaurants();
ListView.DataBind();
}
protected void FilterBtn_Click(object sender, EventArgs e)
{
string filterType = FilterTypeDDL.SelectedValue;
string substring = StringTB.Text.Trim().ToUpper();
Session["ALL"] = false;
Session["FilterType"] = filterType;
Session["Substring"] = substring;
ListView.DataSource = DAORestaurant.GetRestaurants(substring, filterType);
ListView.DataBind();
}
protected void ListView_ItemEditing(object sender, ListViewEditEventArgs e)
{
ListView.EditIndex = e.NewEditIndex;
//SetDataSource();
//ListView.DataBind();
}
protected void ListView_ItemInserting(object sender, ListViewInsertEventArgs e)
{
}
protected void ListView_ItemCanceling(object sender, ListViewCancelEventArgs e)
{
if (e.CancelMode == ListViewCancelMode.CancelingInsert)
{
ListView.InsertItemPosition = InsertItemPosition.None;
}
else
{
ListView.EditIndex = -1;
}
//SetDataSource();
//ListView.DataBind();
}
private void SetDataSource()
{
if ((bool)Session["ALL"])
{
ListView.DataSource = DAORestaurant.GetRestaurants();
}
else
{
ListView.DataSource = DAORestaurant.GetRestaurants((string)Session["Substring"], (string)Session["FilterType"]);
}
}
The code commented out is what i used before, i´ve switched to what you can see now, but the problem still persists. Only when i uncomment those 2 commented lines in each event, the changes apply instantly, but i know i cannot use such a method that many times, and it should not even be there.
Because of the order of execution. Try setting it in the Page_Load event:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack &&
!string.IsNullOrEmpty(Request.Form[NewRestaurantBtn.ClientID]))
{
ListView.InsertItemPosition = InsertItemPosition.LastItem;
}
}

radcombobox always selecting top item on postback

I have an edit page where I set the selected index of a radcombobox (rcb_ParentCompany) based on a value returned from the database. However on postback the text in the combobox keeps changing to the top item in the dataset. Any ideas why?
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
BindOperatingNameComboBox(rcb_OperatingName);
BindParentCompanyComboBox(rcb_ParentCompany);
}
}
protected void btn_Edit_Command(object sender, CommandEventArgs e)
{
Client ClientToEdit = ClientController.ViewClient(int.Parse(e.CommandArgument.ToString()));
//Populate Client fields
txt_ClientName.Text = ClientToEdit.ClientName;
rcb_OperatingName.Text = ClientToEdit.OperatingName;
int ParentCompanyIndex = rcb_ParentCompany.FindItemIndexByValue(ClientToEdit.ParentCompanyID.ToString());
rcb_ParentCompany.SelectedIndex = ParentCompanyIndex;
txt_Address1.Text = ClientToEdit.Address1;
txt_Address2.Text = ClientToEdit.Address2;
txt_Country.Text = ClientToEdit.Country;
txt_Region.Text = ClientToEdit.Region;
txt_City.Text = ClientToEdit.City;
txt_PostalCode.Text = ClientToEdit.PostalCode;
txt_ClientNote.Text = ClientToEdit.ClientNote;
tbl_EditServices.Controls.Clear();
PopulateEditClientPanel(ClientToEdit);
btn_SaveChanges.CommandArgument = e.CommandArgument.ToString();
btn_Cancel.CommandArgument = e.CommandArgument.ToString();
}
protected void BindParentCompanyComboBox(RadComboBox ComboBox)
{
DataTable OperatingNames = ClientController.GetExistingClientAndOperatingNames("");
ComboBox.DataTextField = "ClientName";
ComboBox.DataValueField = "ClientID";
ComboBox.DataSource = OperatingNames;
ComboBox.DataBind();
}
protected void rcb_ParentCompany_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
{
BindParentCompanyComboBox((sender as RadComboBox));
}
Any ideas why?
Yes, because you are doing if(IsPostBack) as opposed to if(!IsPostBack)

Problem with page lifecycle

The qustion was modified by me to show a complete picture.
I have a basic question:
code behind:
protected void Page_Load(object sender, EventArgs e)
{
int firstPageIndex = 0;
int lastPageIndex = 5;
if (TotalPageNumber > 5)
{
if ((TotalPageNumber - PageIndex) <= 5)
firstPageIndex = TotalPageNumber - 5;
firstPageIndex = PageIndex < 3 ? 0 : PageIndex - 2;
}
else
{
firstPageIndex = 0;
lastPageIndex = TotalPageNumber;
}
for (int i = firstPageIndex; i < firstPageIndex + lastPageIndex; i++)
{
LinkButton lnk = new LinkButton();
lnk.CommandArgument = i.ToString();
lnk.Click += new EventHandler(lblPageNumber_Click);
lnk.ID = "lnkPage" + (i + 1).ToString();
lnk.Text = (i + 1).ToString();
plcPagerHolder.Controls.Add(lnk);
} }
int _pageIndex;
public int PageIndex
{
get
{
object objPage = ViewState["_pageIndex"];
if (objPage == null)
{
_pageIndex = 0;
}
else
{
_pageIndex = (int)objPage;
}
return _pageIndex;
}
set {ViewState["_pageIndex"] = value; }
}
protected void lnkPagerNext_Click(object sender, EventArgs e)
{
PageIndex = PageIndex == TotalPageNumber - 1 ? 0 : PageIndex + 1;
}
The problem is with Page_Load event, I expect to get new PageIndex after the linkbutton is clicked.
Update:
My Foo adds new controls to the page, based on provide Page index so I guess I can't put it in Prerender.
Two options
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Foo (PageIndex);
}
}
protected void LinkButton_Click(object sender, EventArgs e)
{
PageIndex = int.Parse(((LinkButton)sender).CommandArgument);
Foo (PageIndex);
}
or
protected void Page_PreRender(object sender, EventArgs e)
{
Foo (PageIndex);
}
you can place Foo (PageIndex) in Page_LoadComplete event instead of Page_Load, i.e.
protected void Page_LoadComplete(object sender, EventArgs e)
{
Foo (PageIndex);
}
LoadComplete event is raised after Control events.
Edit:
LoadComplete is the earliest place where you can safely access new pageindex and also you can add there another controls, but that is possible also in PreRender.
And you will, but Page_Load gets called before the event handler for the linkbutton .. so, you can't really expect it to be changed yet.

Resources