The Name 'data' does not exist in the current context - c#

I am trying to generate a try catch method in a class, But I am facing this error message, Please help me to solve this.
My class is
public string Countryadd(string country, string id)
{
try
{
string data="0";
string qry1 = "select Country from Country where Country='" + country + "'";//Checking weather txtcountry(Country Name) value is already exixst or not. If exist return 1 and not exists go to else condition
SqlDataReader dr = conn.query(qry1);
if (dr.Read())
{
return data = "1";
}
else//If Country Name Not Exists
{
string qry = "insert into Country values('" + id + "','" + country + "')";//Insertin data into database Table Country
conn.nonquery(qry);
}
}
catch (Exception Ex)
{
ShowPopUpMsg(Ex.Message);
}
return data;
}

You need to put the definition of data before the try block:
string data="0";
try {
The {} brackets define the scope of a variable.
You can only access a variable within that scope.

Since you define your data variable in try block, it doesn't seems outside of this blocks. It is only available in try block and any child scope.
You can move it's definition outside of your try-catch block.
string data="0";
try
{
...
}
catch (Exception Ex)
{
ShowPopUpMsg(Ex.Message);
}
return data;
Read: 3.7 Scopes (C#) from MSDN

All variables created between the { } symbols are inside the scope of the symbols themselves.
If you need to use data outside of it, declare it before the try.
string data = string.Empty; // or initialize the value to "0" if that's the default you want.
try
{
// Don't declare data here or it won't be visible outside the try block.
// You can set the "0" or whatever value you want here though.
...
}
catch (Exception Ex)
{
...
}
return data;

data is currently defined within the scope of the try block, you need to move it outside
string data = "0";
try
{
...
}
catch(NullReferenceException ex)
{
}
catch(SomethingRelatedToDataReaderException ex)
{
}
return data;
Also, you shouldn't really try to catch Exception, you should try to catch the specific types of exceptions. This helps to avoid covering up issues as well as giving you more control

The scoping of your variable data is only inside the Try/Catch block because you defined in it.
Try to define the variable data outsiude the block.

Related

what is the best way to initialize object with try, catch block without using block in c#

I have one method, in which I want to initialize object (e.g. fetches Department List) of one Class and use that same in try/catch block (e.g. returns that Department List) and then want to set it to null.
One way
public List<Departments> GetAllDepartments()
{
List<Departments> listDepartments = null;
try
{
listDepartments = IDepartment.GetAllDepartments();
return listDepartments;
}
catch (System.Exception ex)
{
throw ex;
}
finally
{
listDepartments = null;
}
}
Another way
public List<Departments> GetAllDepartments()
{
try
{
List<Departments> listDepartments = IDepartment.GetAllDepartments();
return listDepartments;
}
catch (System.Exception ex)
{
throw ex;
}
}
Which one is best? if any other way, please let me know. I have discussed this same with my office mates, one told me that in 1 method, I forces to compiler to initializes the object (here listDepartment) to set first with null and then forces to compile with database object.
Note: I could not able to use IDisposable.
I am sorry, that I could not able to raise the question very clear in first run. this is just an example of department, actually there are many other filters and other objects in my method. my main concern is, how the compiler will work when first line it catches like ' List listx = null; ' and listx = new xClass(); or listx = [database call]. as my office mates told me this is an extra overhead for compiler. I would like to clear my this doubt here.
Please forget the above question
Here I am redefining my question.
Question:
I and one of my office mate has debate about initialize the object and set it null once it has been utilized.
I suggest him the below way to get release the object once it has been utilized:
public string something()
{
Department objDepartment = null;
try
{
objDepartment = new Department();
}
catch
.
.
.
finally
{
objDepartment = null;
}
}
my office mate told me that, very first here i am forces to .net compiler to initialize the objDepartment with null and after that inside the try block I again force to .net compiler to initialize the objDepartment with actual instance. so according to him the code should be:
public string something()
{
try
{
Department objDepartment = new Department();
}
catch
.
.
.
}
so my question here is: how can i release the object once it has been utilize, as objDepartment will not be available in finally block as its scope is now only inside the try block only. and if any other ways to initialize, use it and release it finally.
and the other condition is that, I could not use IDisposable.
And thanks to all who participated and give the answers. And one more time I expecting your active participation.
public List<Departments> GetAllDepartments()
{
return IDepartment.GetAllDepartments();
}
That is the only useful code in your question. There is no point or benefit in setting a local (aka method-variable) to null before exiting; that serves no purpose, and does not represent "collection" or anything remotely similar - so there is no point in the finally. The catch block is equally useless, unless your explicit intent is to destroy your own stack-trace.
If you need to do extra code on the object prior to returning it:
public List<Departments> GetAllDepartments()
{
var departments = IDepartment.GetAllDepartments();
// TODO: do stuff with "departments" here
return departments;
}
Since you are not doing any custom exception try and catch doesn't make any sense in this case. Hence you can use code as bellow.
public List<Departments> GetAllDepartments()
{
return IDepartment.GetAllDepartments();
}
You can use the below code.It will avoid multiple return statement.
public List<Departments> GetAllDepartments()
{
List<Departments> listDepartments = null;
try
{
listDepartments = IDepartment.GetAllDepartments();
}
catch (System.Exception ex)
{
//Handle your exception
}
return listDepartments;
}
public List<Departments> GetAllDepartments()
{
try
{
return IDepartment.GetAllDepartments();
}
catch (System.Exception ex)
{
// throw ex; dont throw the same caugted exception
}
}

Parameter count does not match Parameter Value count after minor change

I changed the code from this
public override IDataReader getData(int pageId, string pageName)
{
try
{
return ((IDataReader)(SqlHelper.ExecuteReader(ConnectionStringConnectorPool, GetFullyQualifiedName("PageModuleGetAll"),pageId, pageName)));
}
catch (Exception ex)
{
ExceptionController.WriteExceptionToLog(string.Format("SqlDataProvider.cs/GetPageByIdAndName: pageId:{0}, pageName{1}", pageId, pageName), -2, ex);
return null;
}
}
To this
public override IDataReader getData(string sqlMethod, int pageId, string pageName)
{
try
{
return ((IDataReader)(SqlHelper.ExecuteReader(ConnectionStringConnectorPool, GetFullyQualifiedName(sqlMethod),pageId, pageName)));
}
catch (Exception ex)
{
ExceptionController.WriteExceptionToLog(string.Format("SqlDataProvider.cs/GetPageByIdAndName: pageId:{0}, pageName{1}", pageId, pageName), -2, ex);
return null;
}
}
Im calling the method like this
public List<PageModuleInfo> GetAllPageModules(int pageId, string paneName)
{
try
{
return Common.Utilities.CBO.FillCollection<PageModuleInfo>(BLL.Data.DataProvider.Instance().getData("PageModuleGetAll", pageId, paneName));
}
catch (Exception ex)
{
ExceptionController.WriteExceptionToLog(new Exception("PageModuleController.cs/GetAllPageModules:" + System.Environment.NewLine + ex));
return null;
}
}
And now im getting Parameter count does not match Parameter Value count error and im wondering why.
The error indicates that you are using a stored procedure, and have supplied more parameter values than there are parameters declared on the stored procedure.
So: check each of the 3 stored procedures, and double-check how many parameters each takes. If one of them does not take at least 2, that is the problem. In particular, also check for different versions of the same stored procedure; for example, there could be dbo.PageModuleGetAll and johndev.PageModuleGetAll - where johndev.PageModuleGetAll is the updated version with 2 parameters. But if your application is running in with different identity (integrated security, a dedicated sql account, etc) - then it will still be running dbo.PageModuleGetAll
Your method is an override of a base class method, so it's likely that the derived classes function signature does not match the base classes signature.
That would give you a 'Parameter Value count error' because the base classes number of parameters is less than the derived class.

Cannot implicity convert "void" to "bool"

Can anyone point to me what is wrong with the code I have? The first function is on a different aspx file than the second function.
protected void btnManageUsersAddUser_Click(object sender, EventArgs e)
{
if (clsDataLayer.SaveUser(Server.MapPath("PayrollSystem_DB.mdb"), txtManageUsersName.Text, txtManageUsersPassword.Text, ddlSecurityLevel.SelectedValue))
{
lblAddUserMsg.Text = "The user was successfully added";
grdManagePersonnel.DataBind();
}
else
{
lblAddUserMsg.Text = "The user was not successfully added";
}
The following function has originally "bool" instead of "void" but my professor told me to change it to "void" due to error of not all returns a value.
public static void SaveUser(string Database, string UserName, string UserPassword, string SecurityLevel)
{
bool recordSaved;
try
{
// Create connection
OleDbConnection conn = new OleDbConnection("PROVIDER=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Database);
conn.Open();
OleDbCommand command = conn.CreateCommand();
string strSQL;
// Insert to tblUserLogin
strSQL = "Insert into tblUserLogin " +
"(UserName, UserPassword, SecurityLevel) values ('" +
UserName + "', '" + UserPassword + "', '" + SecurityLevel + "')";
// Process data
command.CommandType = CommandType.Text;
command.CommandText = strSQL;
// Add your comments here
command.ExecuteNonQuery();
// Closes the transaction when true
conn.Close();
recordSaved = true;
}
catch (Exception ex)
{
}
}
Since you have changed the method return type to type void, you can no longer use it in the conditional statement you have here:
if (clsDataLayer.SaveUser(Server.MapPath("PayrollSystem_DB.mdb"),
txtManageUsersName.Text, txtManageUsersPassword.Text, ddlSecurityLevel.SelectedValue))
...the conditional expects the expression to be reduced to a boolean value.
Your professor might have had a point that not all paths returned a value in a previous edition of your code. You will need to make sure that all paths return a true or false value if your method returns a boolean. For example, you could modify your code to return a boolean value again and return the following values:
...
return true;
}
catch (Exception ex)
{
return false;
}
...
Note that I have removed the "recordSaved" variable as it was unnecessary; if you are only going to use it in that one spot I would suggest returning the true/false values themselves.
Yes, you changed it to return nothing but then you still expect it to return something because you're still trying to use the result:
if (clsDataLayer.SaveUser( ...
Either change that expectation (losing the ability to return valuable information to the caller), or go back to your original version and ensure all code paths return a value.
Your professor's advice is akin to:
You: My car has a flat tire.
Prof: Well, take the tire off.
You: Er, now my car still won't go.
While the professor's advice to remove the flat tire has indeed fixed the immediate problem (inasmuch as your car no longer has a flat tire), it's not really an adequate solution. Changing things without understanding the root cause (a) of the problem frequently leads to situations like that you currently find yourself in.
Your professor should have advised you to understand why you were getting the error and fix that, rather than opting for a quick fix with ramifications elsewhere.
(a) The root cause of this problem is not that your value returns a boolean value, it's because there's a mismatch between what the caller expects and what the callee delivers.
I disagree with your professors recommendation. Changing the return type of your method to void because all paths do not return a value is like slapping a bandage on an infected cut and expecting it to heal.
A better solution, IMO, would be to ensure that all paths do return a value (either true or false).
For example, in your method, change:
bool recordSaved;
to:
bool recordSaved = false;
Then, if at the end of your try section (before the catch line), add:
recordSaved = true;
Then return recordSaved before exiting the method:
return recordSaved;
With these changes, your method will set the recordSaved value to false; it only gets set to true if the record is saved. Then you can return the value, and use the method in your if check.
The complete code would look something like this:
public static bool SaveUser(string Database, string UserName, string UserPassword, string SecurityLevel)
{
bool recordSaved = false;
try
{
// do your save
recordSaved = true;
}
catch (Exception ex)
{
// Handle the exception (logging, etc)
}
return recordSaved;
}

Variable outside a try catch block loses value

I am having a little problem. I have a function with a string outside a try-catch-finally block that is changed depending on what happens inside the block. Once that is finished, I want to display it. My problem is that the value that was changed in the block returns to the original value it had. How can I fix this?
string error = "No issues";
try{
error = "Correct";
}catch(Exception ex){
error = "Wrong:" + ex.Message.ToString();
}finally{
// Closes connection
}
MessageBox.Show(error);
It's not clear to me, if the string in question declared outside the method. If you are 100% sure, that a new value is given to the string, the following code will probably do the problem you have:
static void Foo(string s)
{
try
{
s = "OK";
}
catch { }
}
static void Main(string[] args)
{
string temp = "??";
Foo(temp);
Console.WriteLine(temp); //prints ??
Console.ReadLine();
}
as you are passing string by value. If you need to change the value you should either:
make a ref parameter:
static void Foo(ref string s)
and call it
Foo(ref temp);
or return the new value from the method:
static string Foo(string s)
{
try
{
s = "OK";
}
catch { }
return s;
}
and call it:
temp = Foo(temp);
The code you posted will show a message box with the text
Correct
if no exceptions are thrown, otherwise the message
Wrong: (plus the exception's message property)
It will never show the message
No issues
because you overwrite the initial value of error in the first line of your try block.
error will never lose a value (as in I guess become null) given the code you post. Eventually error will go out of scope (e.g. when you exit the method that this code is defined in).
UPDATE
I took your code, created a brand-new WinForms project, double-clicked on Form1 to create a Load event handler, and posted in your code like this:
private void Form1_Load(object sender, EventArgs e)
{
string error = "No issues";
try
{
error = "Correct";
}
catch (Exception ex)
{
error = "Wrong:" + ex.Message.ToString();
}
finally
{
// Closes connection
}
MessageBox.Show(error);
}
The result was a message box that said "Correct".
If that is not what you see in your real code, you are not sharing enough code to reproduce the problem.

try-catch blocks with the return type

If I have a method that returns something, like
public DataTable ReturnSomething()
{
try
{
//logic here
return ds.Tables[0];
}
catch (Exception e)
{
ErrorString=e.Message;
}
}
This produces compiler error, obviously because catch{} block does not return anything.
So when I have methods with return values I don't use try-catch block, which is a bad practice. If there is an error, I would like to set error string to that error. But then I need a return value as well. Advice?
Store your return value in a temporary variable like this:
public DataTable ReturnSomething()
{
DataTable returnValue = null;
try
{
//logic here
returnValue = ds.Tables[0];
}
catch (Exception e)
{
ErrorString=e.Message;
}
return returnValue;
}
You should raise/throw the exception in your catch block and handle it in the calling method.
public void invokeFaultyCode()
{
try
{
DataTable dt = ReturnSomething();
}
catch(Exception e)
{
// Print the error message, cleanup, whatever
}
}
public DataTable ReturnSomething() throws Exception
{
try
{
//logic here
return ds.Tables[0];
}
catch (Exception e)
{
ErrorString=e.Message;
throw;
}
}
PS: Sorry for any syntax error, I'm a bit rusty on C#.
You should wrap the caller with a try catch... any exceptions that happen in the routine that is called will bubble out to the caller and you can catch them there.
Personally, I think it is overkill to have a try catch in this routine as you should have the caller handling the exception.
For my example, this would be coded as follows...
private void DoSomething() {
try {
DataTable dt = ReturnSomething();
}
catch (Exception ex) {
}
}
public DataTable ReturnSomething() {
DataTable dt = new DataTable();
// logic here
return dt;
}
The ErrorString variable looks suspiciously like an error code variable. Recommended practice is to use exceptions to pass error information directly, where necessary, rather than storing things off into error codes.
You are effectively doing the same thing with your ErrorString as you would be if you just let the exception be caught by the caller: removing the responsibility of responding to an error from the method itself. This is a good goal to have. But the use of an error string doesn't gain you anything over the use of an exception. In fact, you lose information this way. There are any number of types of errors that could occur, and many have special exceptions associated with them, with their own special properties to hold contextual info about the failure. By just storing off the message in a String, you're losing this information.
So unless your goal is specifically to hide the type of error that is occurring from the caller, you can only gain by letting the exception through.
Another thing to consider is whether this is truly an error scenario. If it is, it's very unlikely that your calling method is going to care at all what the return value is. In which case, you have nothing to worry about by just letting the exception go and not returning anything. If it's NOT really an error scenario, and the caller is just going to continue on and do something else, well, that's for the caller to decide, right? There's still not much benefit to obtain by returning an error string and a dummy DataTable or a null, over throwing the exception with all its contextual failure info.
If you are going to head the "don't throw an exception route" (which I am not necessarily reccomending), you could follow the TryParse approach MS uses.
Something like:
private string FillDataTable(out DataTable results)
{
try
{
results = new DataTable(); //something like this;
return String.Empty;
}
catch (Exception ex)
{
results = null;
return ex.Message;
}
}
It depends on you application. You can return null, an empty DataTable or whatever is suitable under circumstances.
i'd assume you can still set the message, then return null or whatever the c# equivalent is
public DataTable ReturnSomething(){
try {
//logic here
return ds.Tables[0];
} catch (Exception e) {
ErrorString=e.Message;
return null;
}
}
How about this :
public DataTable ReturnSomething(out string errorString)
{
errorString = string.Empty;
DataTable dt = new DataTable();
try
{
//logic here
dt = ds.Tables[0];
}
catch (Exception e)
{
errorString = e.Message;
}
return dt;
}
Since you are cacthing the exception (and not throwing it again) in your example, The outside code assumes everyting is okay and therefor you should return something useful.
If you need to catch the exception there and do somthing that's all fine, but if it's still an error case you should also throw it, or a different exception, perhaps with the one you just caught as InnerException.
I think your code is being run at a sufficiently high level of the call stack and it's blended with UI code. If this is really the case, you could return null in the catch block. However, if you are writing reusable code, you should refactor it so that it doesn't contain UI manipulation and handle the exception at a higher level in the call stack.
You can do it like the sample code below.
public DataTable ReturnSomething(out string OutputDesc)
{
try
{
//logic here
OutputDesc = string.Format("Your Successful Message Here...");
return ds.Tables[0];
}
catch (Exception e)
{
OutputDesc =e.Message;
return null;
}
}
Simple
public DataTable ReturnSomething()
{
try
{
//logic here
return ds.Tables[0];
}
catch (Exception e)
{
ErrorString=e.Message;
throw new Exception(e.Message);
}
}

Categories