1

I have got this code:

public void chyt_data()
    {
        try
        {


            SqlCommand novyprikaz = new SqlCommand("SELECT * FROM zajezd WHERE akce=" + currentrowstring, spojeni);
            spojeni.Open();
            SqlDataReader precti = novyprikaz.ExecuteReader();

            if (precti.Read())
            {

                zakce.Text = precti.GetString(0);
                zname.Text = precti.GetString(2);

         }

     }
     catch (Exception ex)
     {
         MessageBox.Show("Chybové hlášení2: " + ex.Message.ToString());
     }

     spojeni.Close();
   }

if i insert column name in it it like this:

    zakce.Text = precti.GetString("akce"); 

it wouldn't work.

May someone please help me solve this out ? Thank you so much

it gives two errors:

1:Error 1 The best overloaded method match for 'System.Data.Common.DbDataReader.GetString(int)' has some invalid arguments

2: Error 2 Argument 1: cannot convert from 'string' to 'int'

Marek
  • 3,555
  • 17
  • 74
  • 123

4 Answers4

6

You need the GetOrdinal function

zakce.Text = precti.GetString(precti.GetOrdinal("akce"));
zname.Text = precti.GetString(precti.GetOrdinal("name"));
Bob Vale
  • 18,094
  • 1
  • 42
  • 49
2

For things like:

zakce.Text = precti.GetString("akce");

there are several options:

zakce.Text = (string)precti["akce"];

or if you aren't sure that it is a string:

zakce.Text = Convert.ToString(precti["akce"]);

or:

int idx = precti.GetOrdinal("akce");
zakce.Text = precti.GetString(idx);
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
1

SqlDataReader.GetString() method accepts only parameter with int type. So you have to pass column number instead of column name to get the value.

See MSDN for more info.

Andrey Gordeev
  • 30,606
  • 13
  • 135
  • 162
1

Do like this

  if (precti.Read())
        {

            zakce.Text = precti[0].ToString();
            zname.Text = precti[2].ToString();

        }
Rajeev Kumar
  • 4,901
  • 8
  • 48
  • 83