how do we get the Column Size and dataType from getschemaTable?

marcAntoine picture marcAntoine · Jun 20, 2013 · Viewed 15.6k times · Source

I am a newbie and I am trying to retrieve the Column NAme , Size ( max legth ) and DataType from some table in my database , the following code when i execute it expecting it to display all the column types and names ( i didn't find how to refer to the Size , i used ColumnSize but it is said that DataColumn does not contain a definition for this method ) but when executing it , it only displays : IsColumnSetSystem.Boolean this is the code :

private void button1_Click(object sender, EventArgs e)
    {
        string EF = textBox1.Text;

        try{
            //SqlDataAdapter adapter = SetupDataAdapter("SELECT * FROM id_declarant");
     SqlCommand comm = new SqlCommand();
     string connectionString = @"Data Source=.\SQLEXPRESS;Initial Catalog=declaration;Integrated Security=True";
      comm.Connection=new SqlConnection(connectionString);
            String sql = @"SELECT * 
                  FROM id_declarant,declarant
                 WHERE (declarant.Nom_pren_RS='" + EF + "') and (id_declarant.mat_fisc=declarant.mat_fisc)  "; 
     comm.CommandText = sql;
  comm.Connection.Open();
             SqlDataReader reader = comm.ExecuteReader();
             DataTable schemaTable = reader.GetSchemaTable();
             foreach (DataRow row in schemaTable.Rows)
             {
                 foreach (DataColumn column in schemaTable.Columns)
                 {
                     System.IO.File.WriteAllText(@"C:\Users\Manuela\Documents\GL4\WriteLines.txt", column.ColumnName + column.DataType );

                 }
             }

Answer

Ric picture Ric · Jun 20, 2013

Maybe I'm a bit off on this one but to get the name, size and datatype of the column you can try this:

DataTable schemaTable = reader.GetSchemaTable();
foreach (DataRow row in schemaTable.Rows)
{
    var name = row["ColumnName"];
    var size = row["ColumnSize"];
    var dataType = row["DataTypeName"];
    //append these to a string or StringBuilder for writing out later...
}

But maybe this is not what you're after?