How do I define a variable for use everywhere - c#

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;
}

Related

Variable in other function has always value zero

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"];
}

I Need to insert Exception details into sql server database

My issue is that i have an aspx page which is having try and catch bocks in its code file which will handle exception using exception object in catch,now when the program execution reaches this catch block it calls the public method GetExceptionDetails which will return a long string text containing the values of all the properties of exception but not property's name in it.Now when i insert the properties values into table object's field of database everything is right upto the point when the code reaches at db.submitchanges(),in which an exception statement pops out which reads sqldatetimeoverflow and under sqltypesexception.Please help me figure out the issue in this,Below is the whole code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebApplication5
{
public partial class EnterMarks : System.Web.UI.Page
{
public float average,total;
public string grade,chk,exmessage;
DataClasses1DataContext db = new DataClasses1DataContext();
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["StudentID"] != null)
{
Label1.Text = Request.QueryString["StudentID"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
List<int> stdID = new List<int>();
tblGrade tb = new tblGrade();
total = (float)(Convert.ToDouble(TextBox1.Text) + Convert.ToDouble(TextBox2.Text) + Convert.ToDouble(TextBox3.Text));
average = total / 3;
if (average > 85 && average < 90)
{
grade = "AA";
}
else if(average>80 && average<85)
{
grade = "A";
}
else if (average > 75 && average < 80)
{
grade = "BB";
}
else if (average > 70 && average < 75)
{
grade = "B";
}
else if (average > 65 && average < 70)
{
grade = "C";
}
else if (average > 60 && average < 65)
{
grade = "CC";
}
else if (average > 55 && average < 60)
{
grade = "D";
}
else
{
grade = "DD";
}
//var query = from m in db.tblGrades
// where m.StudentID == Convert.ToInt32(Request.QueryString["StudentID"])
// select m;
// foreach (var q in query)
//{
tb.StudentID = Convert.ToInt32(Request.QueryString["StudentID"]);
tb.Grade = grade;
db.tblGrades.InsertOnSubmit(tb);
db.SubmitChanges();
Response.Redirect("WebForm1.aspx");
}
protected void Button2_Click(object sender, EventArgs e)
{
//var query1 = from n in db.tblContacts where n.StudentID == int.Parse(TextBox4.Text) select n;
tblExcDet te = new tblExcDet();
var query1 = from n in db.tblContacts select n.StudentID;
//try
//{
foreach (var q in query1)
{
if (q.Equals((int.Parse(TextBox4.Text))))
{
Label2.Text = "ID Found";
}
}
try
{
int? i = null;
tblContact tc = new tblContact();
tc.StudentID = (int)i ;
//db.tblContacts.InsertOnSubmit(tc);
db.SubmitChanges();
}
catch (Exception ex)
{
exmessage = GetExceptionDetails(ex);
te.ExMessage = exmessage.Split('*')[0];
te.ExData = exmessage.Split('*')[1];
te.ExInner = exmessage.Split('*')[2];
te.ExTargetSite = exmessage.Split('*')[3];
te.ExStackTrace = exmessage.Split('*')[4];
te.ExHelplink = exmessage.Split('*')[5];
te.ExSource = exmessage.Split('*')[6];
te.ExHresult = exmessage.Split('*')[7];
db.tblExcDets.InsertOnSubmit(te);
db.SubmitChanges();
Label2.Text = "Can't assign null value into a table id";
}
}
//public static string GetExceptionDetails(Exception ex)
//{
// var properties = ex.GetType().GetProperties();
// var fields = properties.Select(property=>new{
// name = property.Name,value = property.GetValue(ex,null)
// }).Select(x => String.Format(
// "{0} = {1}",
// x.name,
// x.value != null ? x.value.ToString() : String.Empty
// ));
// return String.Join("*", fields);
//}
public static string GetExceptionDetails(Exception ex)
{
var properties = ex.GetType().GetProperties();
var fields = properties.Select(property => new
{
name = property.Name,
value = property.GetValue(ex, null)
}).Select(x => String.Format(
"{0}",
x.value != null ? x.value.ToString() : String.Empty
));
return String.Join("*", fields);
}
}
}
Also here i'm using LINQ structure to insert data into sql server database.
Do you have the field set as autogenerated in the designer? If that's not the problem, I'd suggest setting up logging of the data context actions to the console and checking the actual SQL generated to make sure that it's inserting that column, then trace backward to find the problem.
context.Log = Console.Out;
FWIW, I often set my "CreatedTime" and "LastUpdatedTime" columns up as autogenerated (and readonly) in the designer and give them a suitable default or use a DB trigger to set the value on insert or update. When you set it up as autogenerated, it won't include it in the insert/update even if modified. If the column doesn't allow nulls, then you need to supply an alternate means of setting the value, thus the default constraint and/or trigger.
You might also want to try an explicit cast to
SqlDbType.DateTime
before doing updatechanges

How to Load all the Objects in an Array List

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--;
}

Page Counter not working ASP.NET C#

everybody. I've been trying to follow exactly what it says in my textbook, but to no avail. Now, my problem is that I'm currently attempting to make a page counter to keep track of how many times each page has been accessed, then display each value on a new page.
Here is the C# Counter code which is the same for all pages:
int sessionCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["CountMain"] == null)
sessionCount = 0;
else
sessionCount = Convert.ToInt32(Session["CountMain"]);
sessionCount++;
}
protected void Page_PreRender(object sender, EventArgs e)
{
Session["CountMain"] = sessionCount;
}
The prerender is something I added in myself after research on the internet, and in the textbook. No luck.
Here is the Counter Page C# code:
public partial class Counter : System.Web.UI.Page
{
int sessionCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
string sessionMain = Session["CountMain"].ToString();
string sessionComment = Session["CountComment"].ToString();
string sessionCompleted = Session["CountCompleted"].ToString();
string sessionCurrent = Session["CountCurrent"].ToString();
string sessionAbout = Session["CountAbout"].ToString();
string sessionContact = Session["CountContact"].ToString();
string sessionCounter = Session["CountCounter"].ToString();
if (Session["CountCounter"] == null)
sessionCount = 0;
else
sessionCount = Convert.ToInt32(Session["CountCounter"]);
sessionCount++;
lblAboutCount.Text = sessionAbout;
lblCommentCount.Text = sessionComment;
lblCompletedCount.Text = sessionCompleted;
lblContactCount.Text = sessionContact;
lblCounterCount.Text = sessionCounter;
lblCurrentCount.Text = sessionCurrent;
lblMainCount.Text = sessionMain;
}
When I try to run it, I get a "NullReferenceException was unhandled by user code, Object reference not set to an instance of an object." Error.
Thanks in advance.
EDIT #1
Okay, Thanks to Hexxangonal, the counter is now working. However, my Counter Page is now counting it self by 2 times. (incrementing by 2 every time it loads)
public partial class Counter : System.Web.UI.Page
{
int sessionCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["CountCounter"] == null)
{
sessionCount = 0;
Session["CountCounter"] = sessionCount;
}
else
{
sessionCount = Convert.ToInt32(Session["CountCounter"]);
sessionCount++;
Session["CountCounter"] = sessionCount;
}
Session["CountCounter"] = sessionCount;
lblAboutCount.Text = Convert.ToString(Session["CountAbout"]);
lblCommentCount.Text = Convert.ToString(Session["CountComment"]);
lblCompletedCount.Text = Convert.ToString(Session["CountCompleted"]);
lblContactCount.Text = Convert.ToString(Session["CountContact"]);
lblCounterCount.Text = Convert.ToString(Session["CountCounter"]);
lblCurrentCount.Text = Convert.ToString(Session["CountCurrent"]);
lblMainCount.Text = Convert.ToString(Session["CountMain"]);
}
The NullReference exception is probably coming from one of your Session["CountXXXXX"].ToString() lines (CountXXXXX is one of your count objects like CountMain) because Session["CountXXXXX"] does not exist (it is null).
You can actually simplify that page to the following logic and you will bypass the issue as the null will just be assigned to the string variable.
public partial class Counter : System.Web.UI.Page
{
int sessionCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["CountCounter"] == null)
sessionCount = 0;
else
sessionCount = Convert.ToInt32(Session["CountCounter"]);
sessionCount++;
// **NEW** Save the new count value
Session["CountCounter"] = sessionCount;
lblAboutCount.Text = Session["CountAbout"];
lblCommentCount.Text = Session["CountComment"];
lblCompletedCount.Text = Session["CountCompleted"];
lblContactCount.Text = Session["CountContact"];
lblCounterCount.Text = sessionCounter;
lblCurrentCount.Text = Session["CountCurrent"];
lblMainCount.Text = Session["CountMain"];
}
There was also an issue where you were mixing integers and strings with the sessionCount variable with a member variable and a local variable (respectively). I have cleaned this up.
The problem is with these two lines
if (Session["CountCounter"] == null)
sessionCount = 0;
else
sessionCount = Convert.ToInt32(Session["CountCounter"]);
sessionCount++;
You are not putting back these values into the session variable.
You should be doing as follows:-
if (Session["CountCounter"] == null)
{
sessionCount = 0;
Session["CountCounter"]=sessionCount;
}
else
{
sessionCount = Convert.ToInt32(Session["CountCounter"]);
sessionCount++;
Session["CountCounter"]=sessionCount;
}

changing CSS class for object sender control

i'm making a workbook creator in C#.net ( using visual studio )
the book is build from the text part and the question part.
all the answers for the question are inside the text and the user need to click on the right answer. if he's right then the word become green and if he's wrong it become red.
i'm creating the clickeable text with LINKBUTTON, i gave the link button CssStyle class and after the user clicking the word i want to change the class for this link to a different class.
this is the code i using for creating the linksbutton:
public void createQusetion(Panel lefttext, Panel question, string text, string
questionText, string answer)
{
string[] Qbuttonstext = text.Split(' ');
_numberWords = Qbuttonstext.Length;
for (int i = 0; i < _numberWords; i++)
{
LinkButton answerButton = new LinkButton();
if (Qbuttonstext[i] == answer)
{
answerButton.ID = "answer" + i;
}
else
{
answerButton.ID = "word" + i.ToString();
}
answerButton.Text = Qbuttonstext[i].ToString() + " ";
answerButton.CssClass = "textbuttonB4";
answerButton.Click += new EventHandler(checkAnswer);
lefttext.Controls.Add(answerButton);
}
}
and for the checking the question:
private void checkAnswer(object sender, System.EventArgs e)
{
for (int i = 0; i < _numberWords; i++)
{
if (((Control)sender).ID.ToString() != null)
{
if (((Control)sender).ID.ToString() == "answer" + i.ToString())
{
((Control)sender).CssClass = "textbuttonRight";
}
else
{
((Control)sender).CssClass = "textbuttonwrong";
}
}
}
}
the VS2010 giving me misatake for the : ((Control)sender).CssClass .
what is the right way?
You can do a type-independent control this way. It will run for all controls have Id and CssClass Properties.
private void checkAnswer(object sender, System.EventArgs e)
{
var cssClass = sender.GetType().GetProperty("CssClass");
var id = sender.GetType().GetProperty("ID").GetValue(sender, null);
for (int i = 0; i < _numberWords; i++)
{
if (id!=null)
{
if (id.ToString() == "answer" + i.ToString())
{
cssClass.SetValue(sender, "textbuttonRight", null);
}
else
{
cssClass.SetValue(sender, "textbuttonRight", null);
}
}
}
}

Categories