Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a specific column value from a DataTable in c#

Tags:

c#

datatable

How to get a specific column value from a DataTable in c#

I have a problem with my code C#.

I need read a specific column value from a DataTable.

I've tried using this solution without success, because the output is the name of column selected in the query (File) and not the value of field database.

I would greatly appreciate any help you can give me in working this problem.

Here is my code:

public DataTable GridViewBind()
{
    using (OdbcConnection cn =
        new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
    {    
        sql1 = " SELECT FILE FROM tbl_A WHERE Id = 1; ";


        using (OdbcDataAdapter command =
            new OdbcDataAdapter(sql1, cn))
        {
            try
            {
                cn.Open();

                dset = new DataSet();
                dset.Clear();
                command.Fill(dset);
                DataTable dt = dset.Tables[0];
                GridView1.DataSource = dt;                    
                GridView1.DataBind();

                Response.Write(dt.Columns[0].ToString());

                return dt;
            }
            catch (Exception ex)
            {
                throw new ApplicationException("operation failed!", ex);
            }
            finally
            {
                if (command != null)
                {
                    command.Dispose();
                }

                if (cn != null)
                {
                    cn.Close();
                    cn.Dispose();
                }
            }
        }
    }
}

Edit #1

Now I have error:

System.IndexOutOfRangeException: There is no row at position 0.

public DataTable GridViewBind()
{
    using (OdbcConnection cn =
        new OdbcConnection(ConfigurationManager.ConnectionStrings["cn"].ConnectionString))
    {    
        sql1 = " SELECT FILE FROM tbl_A WHERE Id = 1; ";


        using (OdbcDataAdapter command =
            new OdbcDataAdapter(sql1, cn))
        {
            try
            {
                cn.Open();

                dset = new DataSet();
                dset.Clear();
                command.Fill(dset);
                DataTable dt = dset.Tables[0];
                GridView1.DataSource = dt;                    
                GridView1.DataBind();

                string file = dt.Rows[0].Field<string>(0);
                Response.Write(file.ToString());  

                return dt;
            }
            catch (Exception ex)
            {
                throw new ApplicationException("operation failed!", ex);
            }
            finally
            {
                if (command != null)
                {
                    command.Dispose();
                }

                if (cn != null)
                {
                    cn.Close();
                    cn.Dispose();
                }
            }
        }
    }
}
like image 973
Hamamelis Avatar asked Aug 26 '14 12:08

Hamamelis


People also ask

How to select specific column value from DataTable in c#?

string countryName = "USA"; DataTable dt = new DataTable(); int id = (from DataRow dr in dt. Rows where (string)dr["CountryName"] == countryName select (int)dr["id"]). FirstOrDefault();

How to get column from DataTable?

The DataTables columns() and column() (also optionally cells() and cell() ) methods provide the ability to select columns from the table. Which columns are selected and how the selector actually operates is controlled by this column-selector data type.

How get unique values from DataTable?

Get distinct Product from this Dataset, DataTable distinctDT = SelectDistinct(dsOrders. Tables[0], "Product");


1 Answers

The table normally contains multiple rows. Use a loop and use row.Field<string>(0) to access the value of each row.

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>("File");
}

You can also access it via index:

foreach(DataRow row in dt.Rows)
{
    string file = row.Field<string>(0);
}

If you expect only one row, you can also use the indexer of DataRowCollection:

string file = dt.Rows[0].Field<string>(0); 

Since this fails if the table is empty, use dt.Rows.Count to check if there is a row:

if(dt.Rows.Count > 0)
    file = dt.Rows[0].Field<string>(0);
like image 79
Tim Schmelter Avatar answered Oct 25 '22 15:10

Tim Schmelter