Search code examples
c#sqlsqlcommandgetstring

Can't put column name into GetString


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'


Solution

  • You need the GetOrdinal function

    zakce.Text = precti.GetString(precti.GetOrdinal("akce"));
    zname.Text = precti.GetString(precti.GetOrdinal("name"));