Question

I need to know the original type of each column in my DataGridView.

It is bound with a dynamic SQL select, say, "SELECT * FROM artists;"

I want to add a form view of the data above the grid and am programmtically creating Labels and TextBoxes and then some to hold the fields. I add them to a FlowLayoutPanel but I would like to adapt the sizes, especially the multiline property and the height to accomodate long comment and description fields of say 200-500 characters.

All I found when looking into the text columns was datatype string.

I know I can look up the columns by querying the systables, but it would be nice to find the original datatype a bit closer than that; also I'm using MYSQL atm, and a solution that doesn't need to query the database would hopefully also be DBMS independent.

Edit 1

I fill the DGV with nothing fancy:

DBDA = new MySqlDataAdapter(sql, DBC);
MySqlCommandBuilder cb = new MySqlCommandBuilder(DBDA);
DBDS = new DataSet(ddlb_tables.Text);
DBDA.FillSchema(DBDS, SchemaType.Mapped);  //<- This was the missing piece of code!!
DBDA.Fill(DBDS, ddlb_tables.Text);
dataGridView1.DataSource = DBDS;
dataGridView1.DataMember = ddlb_tables.Text;

Edit 2

With the help of the accepted answer (DBDA.MissingSchemaAction) I could solve my problem. Here is the resulting function in its first, raw version:

public int getColumnSize(DataGridViewColumn dc)
{
  try
  {
    DataGridView DGV = dc.DataGridView;
    DataSet DS = (DataSet)DGV.DataSource;
    DataTable DT = DS.Tables[0];
    DataColumn DC = DT.Columns[dc.Name];
    return DC.MaxLength;
  } catch { }
  return -1;
}

Not getting the original type is not a problem, as long as I know the length of the fields.

Was it helpful?

Solution

use the DataSet instead DataGrid:

foreach (DataColumn col in DBDS[ddlb_tables.Text].Text.Columns)
{
    if (col.DataType == typeof(string))
    {
        var len = col.MaxLenght;
        ...
    }
}

EDIT:

You may need to add the following line before filling:

   DBDA.MissingSchemaAction = MissingSchemaAction.AddWithKey;

Source: The DataAdapter.Fill method does not set all of the properties of the DataTable and DataColumn objects

EDIT 2:

Or for result sets without a key:

   DBDA.FillSchema(DBDS, SchemaType.Source);

Or:

   DBDA.FillSchema(DBDS, SchemaType.Mapped);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top