Вопрос

I have this method which selects year, and I need this result to be accesible for rest of methods. I tried this:

    void choose_year()
        {
    SqlCommand chooseyear = new SqlCommand("SELECT year FROM firma WHERE id=1", spojeni);

            spojeni.Open();

            int? year= (int?)chooseyear .ExecuteScalar();

            spojeni.Close();
}

and into my public partial class placed public int I placed "public int year;"

public partial class tours : Form
{


    SqlConnection spojeni = new SqlConnection(myConnection.DataSource.ConnectionString);


    public int year;

When I try to access the result from another method like this:

void choose_tour()
    {


        DataTable dt = new DataTable();
        SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM zajezd WHERE year="+year, spojeni);
        SDA.Fill(dt);
  }

It returns different value like -1, 1 or 0 I'm not sure exactly but the value when I do choose_year() the result should be 2013. When I place SqlCommand for choose_year into method that I use it for exactly for choose_tour the result is 2013 as it should be. What am I doing wrong? Thank you so much for your time and advice.

I thought when I do public int year; with the same name as is result in choose_year() it will unite. I'm not programming for long time so I'm sorry for my faults.

Это было полезно?

Решение

in the choose_year() method you have

int? year= (int?)chooseyear.ExecuteScalar();

the int? before means you are declaring another variable to hold the value of the year the code that you you want is probably this

Object mayBeNullYear = chooseyear.ExecuteScalar();
if(mayBeNullYear!=null)
this.year= (int)mayBeNullYear;

Другие советы

Your method should return a year like for example

     int choose_year()
            {
        SqlCommand chooseyear = new SqlCommand("SELECT year FROM firma WHERE id=1", spojeni);

                spojeni.Open();

                int? year= (int?)chooseyear .ExecuteScalar();

                spojeni.Close();
return year;
    }

And then you call this inside those functions where you need that year for example

void choose_tour()
    {

        int year =   choose_year();
        DataTable dt = new DataTable();
        SqlDataAdapter SDA = new SqlDataAdapter("SELECT * FROM zajezd WHERE year="+year, spojeni);
        SDA.Fill(dt);
  }

try it should work

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top