I have problem with one variable.
protected void godziny_Click(object sender, EventArgs e)
{
var id_filmu = Request["id"];
var data = Request["data"];
var godzina = TimeSpan.Parse(hidden2.Value);
var query = from h in bazaDC.seanses
where h.godzina == godzina && h.id_filmu == int.Parse(id_filmu) && h.data == DateTime.Parse(data)
select h;
foreach (var a in query)
{
Session["id_seansu"] = a.id_seansu;
}
}
id_seansu is declared outside function, just in partial class. I have to get that variable in another function:
protected void rezerwujButton_Click(object sender, EventArgs e)
{
DateTime dzisiejszaData = DateTime.Today;
TimeSpan godzinaRezerwacji = DateTime.Now.TimeOfDay;
DateTime dataZarezerwowania;
TimeSpan czasZarezerwowania;
var query = from wszystkieRezerwacje in bazaDC.rezerwacjes
select wszystkieRezerwacje;
foreach(var i in query)
{
if(i.data_rezerwacji.HasValue && i.czas_rezerwacji.HasValue)
{
dataZarezerwowania = i.data_rezerwacji.Value;
czasZarezerwowania = i.czas_rezerwacji.Value;
}
}
rezerwacje nowaRezerwacja = new rezerwacje();
if (Session["id_seansu"] != null)
{
Response.Write(Session["id_seansu"]);
};
/*nowaRezerwacja.imie_klienta = imieTextBox.Text;
nowaRezerwacja.nazwisko_klienta = nazwiskoTextBox.Text;
nowaRezerwacja.email_klienta = emailTextBox.Text;
nowaRezerwacja.nrtel_klienta = nrKomTextBox.Text;
nowaRezerwacja.numer_miejsca = Hidden1.Value;
nowaRezerwacja.data_rezerwacji = dzisiejszaData;
nowaRezerwacja.czas_rezerwacji = godzinaRezerwacji;
nowaRezerwacja.id_seansu = id_seansu;
bazaDC.rezerwacjes.InsertOnSubmit(nowaRezerwacja);
bazaDC.SubmitChanges();*/
}
But when I wanna write that variable by Response.Write("id_seansu") in rezerwujButton_Click It is always "0".
But when I wanna write it in godziny_Click It have correct value.
Why variable is getting 0 value in another function?
When you perform the first click, the page will post back and hence the value of the variable get reset, to Persist Variable on Postback you have to use either session or ViewState, if the you want this variable in other pages then you can go ahead with session if it is specifically for this page then you have to opt ViewState. You can assign like this:
ViewState.Add("id_seansu","some value");
And get value like this:
if (ViewState["id_seansu"] != null)
{
var id_seansu = ViewState["id_seansu"];
}
Related
I am trying to figure out how to load through an Array List of Objects. I am able to retrieve the last Object in the Array, but it will not let me Load any other Object after that. here is part of the code I have. As you can see it saves the object to the List, but when I click the loadLastBtn it will only load the most recent entry and if I hit it again after that nothing loads.
List<Members> lstMembers = new List<Members>();
private int hold;
private void submitBtn_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(firstNameTxt.Text) || string.IsNullOrEmpty(lastNameTxt.Text)
|| string.IsNullOrEmpty(userNameTxt.Text) ||
string.IsNullOrEmpty(passwordTxt.Text) || string.IsNullOrEmpty(confPassTxt.Text)
|| string.IsNullOrEmpty(majorBox.Text) || string.IsNullOrEmpty(specialtyBox.Text))
{
MessageBox.Show("You must enter in all fields before moving forward");
}
else
{
Members m1 = new Members(firstNameTxt.Text, lastNameTxt.Text, userNameTxt.Text,
passwordTxt.Text, confPassTxt.Text, majorBox.Text,
specialtyBox.Text);
lstMembers.Add(m1);
}
}
private void loadLastBtn_Click(object sender, EventArgs e)
{
firstNameTxt.Text = lstMembers[hold].FirstName;
lastNameTxt.Text = lstMembers[hold].LastName;
userNameTxt.Text = lstMembers[hold].UserName;
passwordTxt.Text = lstMembers[hold].Password;
confPassTxt.Text = lstMembers[hold].ConfPassword;
majorBox.Text = lstMembers[hold].Major;
specialtyBox.Text = lstMembers[hold].Specialty;
hold++;
}
I have edited my answer. this will now print each user one by one each time I hit loadLastBtn, but it does show them from the first user to the last, where I need it to shower the last user to the first.
What you need is something like this:
// -1 Indicates that you should start at the end of the list
int index = -1;
private void loadButton_Click(object sender, EventArgs e)
{
if (members != null && members.Count > 0) // Avoid accessing if list is empty or null
{
if (index == -1)
index = members.Count - 1;
firstNameTxt.Text = lstMembers[index].FirstName;
lastNameTxt.Text = lstMembers[index].LastName;
userNameTxt.Text = lstMembers[index].UserName;
passwordTxt.Text = lstMembers[index].Password;
confPassTxt.Text = lstMembers[index].ConfPassword;
majorBox.Text = lstMembers[index].Major;
specialtyBox.Text = lstMembers[index].Specialty;
if (index == 0) // Reached beginning of array
index = -1; // Indicate that next time the last element must be accessed
else
--index;
}
}
private int hold = lstMembers.Count -1;
private void loadLastBtn_Click(object sender, EventArgs e)
{
firstNameTxt.Text = lstMembers[hold].FirstName;
lastNameTxt.Text = lstMembers[hold].LastName;
userNameTxt.Text = lstMembers[hold].UserName;
passwordTxt.Text = lstMembers[hold].Password;
confPassTxt.Text = lstMembers[hold].ConfPassword;
majorBox.Text = lstMembers[hold].Major;
specialtyBox.Text = lstMembers[hold].Specialty;
hold--;
}
I'm trying to create an application where you press the next button and it shows the next object in a list. In this case an object of Employee, I'm using Linq To SQL. I've read about MoveNext, but I don't know how it works and I tried something else which doesn't work (code below). Basically I want to have a next/previous button to get employees from the db.
Here's the code to get all Employees:
public List<Employee> GetEmployees()
{
var q =
from a in db.GetTable<Employee>()
select a;
List<Employee> employeeList = q.ToList();
return employeeList;
}
Button click:
private void btnNext_Click(object sender, EventArgs e)
{
Increment();
LoadEmployee();
}
Increment (method) (this is my solution for getting the next object, but it isn't optimal at all):
public void Increment()
{
if (con.GetEmployee(id) != null)
{
id++;
}
else
{
id += 2;
}
}
LoadEmployee (method):
public void LoadEmployee()
{
Employee e = con.GetEmployees().FirstOrDefault(f => f.id.Equals(id));
tbId.Text = e.id.ToString();
tbFname.Text = e.Fname;
tbLname.Text = e.Lname;
tbDate.Text = e.Date;
}
Sir, try this
public void LoadEmployee()
{
Employee e = con.GetEmployees();
tbId.Text = e[id].id.ToString();
tbFname.Text = e[id].Fname;
tbLname.Text = e[id].Lname;
tbDate.Text = e[id].Date;
}
use id as an index of your collection
So to summarise:
You're using SQL
And want to take a record with 'next' / 'prev'.
If you look at SQL itself without using cursors, I'd say that translates as a 'skip' and 'take 1'. Linq has these features:
// initialize index
int x = -1;
// move next:
var currentEmployee = context.Employees.Skip(++x).FirstOrDefault();
if (currentEmployee == null)
{
// End.
}
// move prev:
if (--x < 0)
{
// move back past start
x = 0;
}
var currentEmployee = context.Employees.Skip(x).FirstOrDefault();
if (currentEmployee == null)
{
// No elements
}
In my project I have 3 user controls, those are displayed in master page. When I entered the value in textbox it doesn't getting current value, it will display previous value.
Code:
1st Data Bound:
protected void dlFirstZone_ItemDataBound(object sender, DataListItemEventArgs e)
{
if (((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem)) && (e.Item.DataItem != null))
{
using (GroceriesServiceClient groceriesServiceClient = new GroceriesServiceClient())
{
HomeMaster pp = (HomeMaster)e.Item.DataItem;
int prdItem = pp.ProductId;
ShoppingCart shopingCartParameter = new ShoppingCart();
//if (pp.DisplayOrder == 1)
//{
Products products = new Products();
if (basePage.BasePageWebSession != null)
{
shopingCartParameter.UserId = Convert.ToInt32(basePage.BasePageWebSession.UserId);
cartlist = groceriesServiceClient.ShoppingCart_UserProductsList(shopingCartParameter);
var td = (from c in cartlist
where c.ProductId == prdItem
select c);
if (td.ToList().Count > 0)
{
TextBox txtQtyDataview = (TextBox)e.Item.FindControl("txtQty");
txtQtyDataview.Text = td.First().Quantity.ToString();
}
}
//}
//else
}
}
}
2nd ItemCommand event handler:
protected void dlProduct_ItemCommand(object source, DataListCommandEventArgs e)
{
HomeMaster q = (HomeMaster)e.Item.DataItem;
if (e.CommandName == "AddToCart")
{
using (GroceriesServiceClient gsc = new GroceriesServiceClient())
{
ShoppingCart shoppingcart = new ShoppingCart();
shoppingcart.UserId = basePage.BasePageWebSession.UserId;
shoppingcart.UserName = basePage.BasePageWebSession.UserName;
shoppingcart.ProductId = Convert.ToInt32(Convert.ToInt32(dlProductDataView.DataKeys[e.Item.ItemIndex]));
TextBox tb1 = (TextBox)e.Item.FindControl("txtQty");
if (!string.IsNullOrEmpty(tb1.Text))
shoppingcart.Quantity = Convert.ToInt32(tb1.Text);
else
shoppingcart.Quantity = 1;
shoppingcart = gsc.ShoppingCart_InsertOrUpdate(shoppingcart);
Response.Redirect(Request.RawUrl);
}
}
}
You can use findControl to find the textbox within a user control, like this (assuming you have a textbox called tb1 in a userconrol called uc1:
me.uc1.findControl("tb1").text
The better way, though, is to expose a public function that can be called to return the value:
In UserControl, create a public function:
public function getValue() as string
return me.tb1.text
end Function
Then you can access it from any page or control that has a reference to the user control:
dim whatsMyName as string = me.uc1.getValue()
According to below code , after getting some value (newrev,newreview) and putting in the variable, I need to put them in the label ("some text"+newrev). But I have problem (newrev) does not exist in current context.
Label1.Text = "Review Number:" + newReview + "(for preparing of Rev." + newrev+")";
protected void ddlProjectDocument_SelectedIndexChanged(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
var x = ddlProjectDocument.SelectedValue;
var MaxRev = (from rev in _DataContext.tblTransmittalls
where rev.DocID.ToString() == ddlProjectDocument.SelectedValue
select rev.REV).Max();
if (MaxRev == null)
{
var newRev = 0;
}
else
{
var newRev = Convert.ToInt32(MaxRev) + 1;
}
var MaxReview = (from rev in _DataContext.tblFiles
where (rev.DocId.ToString()==ddlProjectDocument.SelectedValue)&&
(rev.Rev.ToString()==MaxRev)
select rev.Review).Max();
if (MaxReview == null)
{
var newReview = 1;
}
else
{
var newReview = Convert.ToInt32(MaxReview) + 1;
}
Label1.Text = "Review Number:" + newReview + "(for preparing of Rev." + newrev+")";
}
Define newRev and newReview in the begining of your function like this:
protected void ddlProjectDocument_SelectedIndexChanged(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
int newRev;
int newReview;
Then when you want to use them, instead of writing var newReview = ... (which declares a new variable) remove the var... e.g.:
if (MaxReview == null)
{
newReview = 1;
}
The difference:
Every variable that is declared has a Scope, which determines its visibility to the rest of a program. In your case, the newReview is known only inside the if statement, so when you try to reference it outside, it no longer exists.
You need to declare newRev outside the if statement.
int newrev;
if(MaxRev == null)
newRev = 0;
else
newRev = Convert.ToInt32(MaxRev) + 1;
C# is not JavaScript, you should use less "var"...
You are defining your newRev inside
if (MaxRev == null)
{
var newRev = 0;
}
define it here
protected void ddlProjectDocument_SelectedIndexChanged(object sender, EventArgs e)
{
_DataContext = new EDMSDataContext();
var newRev = 0;
....
}
it's because you're declaring newRev within various if statements, declare it at the outer level:
int newRev;
if (MaxRev == null)
{
newRev = 0;
}
when i work with selectionchanged event in datagridview.
if i click column header it give me that exception:
NullReferenceException was unhandled by user code
Object reference not set to an instance of an object.
it is my code
private void dgvEvents_SelectionChanged(object sender, EventArgs e)
{
//
//Select By EventID Operation.
//
eventID = int.Parse(dgvEvents.Rows[dgvEvents.CurrentRow.Index].Cells["EventID"].Value.ToString());
EventEntity = EventsMethods.SelectByID(eventID);
txtEventName.Text = EventEntity.Name;
cboxEventsCategories.SelectedValue = EventEntity.EventCategoryID;
dateTimePickerEvent.Text = EventEntity.Date.ToString();
txtBenefNum.Text = EventEntity.BeneficiariesNumber.ToString();
txtResultB.Text = EventEntity.ResultBefore.ToString();
txtResultA.Text = EventEntity.ResultAfter.ToString();
txtPercentage.Text = EventEntity.Percentage.ToString();
//
//Show EventsMembers.
//
FillEventsMembersDGV();
}
one of these is returning a null object...
dgvEvents.Rows[dgvEvents.CurrentRow.Index].Cells["EventID"].Value.ToString()
could be any one of these:
dgvEvents
dgvEvents.CurrentRow
dgvEvents.Rows[....]
dgvEvents.Rows[....].Cells
dgvEvents.Rows[....].Cells["EventID"]
dgvEvents.Rows[....].Cells["EventID"].Value
best way to find out, would be to break it into steps:
var curRow= dvgEvents.CurrentRow;
if ( curRow != null )
var index = curRow.Index;
// etc
You're likely getting this error because its trigger the event when it's not a valid selection (ie. -1) thus throwing this exception. Try this:
if ((e.RowIndex >= 0) && (e.ColumnIndex >= 0))
{
//
//Select By EventID Operation.
//
//Also, use Convert.ToString() rather than .ToString();
eventID = int.Parse(Convert.ToString(dgvEvents.Rows[dgvEvents.CurrentRow.Index].Cells["EventID"].Value));
EventEntity = EventsMethods.SelectByID(eventID);
txtEventName.Text = EventEntity.Name;
cboxEventsCategories.SelectedValue = EventEntity.EventCategoryID;
dateTimePickerEvent.Text = EventEntity.Date.ToString();
txtBenefNum.Text = EventEntity.BeneficiariesNumber.ToString();
txtResultB.Text = EventEntity.ResultBefore.ToString();
txtResultA.Text = EventEntity.ResultAfter.ToString();
txtPercentage.Text = EventEntity.Percentage.ToString();
//
//Show EventsMembers.
//
FillEventsMembersDGV();
}