Error trying to add a self-incrementing column to a datagridview

0

I'm trying to add a autoincrementable column in a datagridview but I can not figure out what's missing to work properly. My program reads the data from a database table and displays it in datagridview . I need to add a autoincrementable column called 'Legend' because table values are also represented in a graph and the 'Legend' column exists to facilitate user interpretation of the data.

Follow part of the code responsible for this. The column named 'Legend' appears in datagridview , but the lines are left blank.

Conexao ca = new Conexao();
string sql = "";
sql += " Select ";
sql += " CausaDef, Incidencia ";
sql += " From ";
sql += " Relat ";

ca.Conectar();
OleDbDataAdapter da = new OleDbDataAdapter(sql, ca.cx);
DataSet ds = new DataSet();
da.Fill(ds, "DetGraf");

object sumObject;
sumObject = ds.Tables["DetGraf"].Compute("Sum(Incidencia)", "");

ds.Tables["DetGraf"].Rows.Add("TOTAL", sumObject.ToString());

DataColumn Legenda = new DataColumn();
Legenda.ColumnName = "Legenda";
Legenda.DataType = typeof(int);
Legenda.AutoIncrement = true;
Legenda.AutoIncrementSeed = 1;
Legenda.AutoIncrementStep = 1;

ds.Tables["DetGraf"].Columns.Add(Legenda);

dgvDetGraf.DataSource = ds.Tables["DetGraf"];

ca.Desconectar();
    
asked by anonymous 30.05.2016 / 18:53

2 answers

0

I was able to find a solution like this:

ds.Tables["DetGraf"].Columns.Add(Legenda);

int index = 0;
foreach (DataRow row in ds.Tables["DetGraf"].Rows)
row.SetField(Legenda, ++index);

dgvDetGraf.DataSource = ds.Tables["DetGraf"];

Abs!

    
03.06.2016 / 20:03
0

Try to modify the code, instead of creating this column "auto-increment", try to bring the line number of the database through the ROW_NUMBER function if it is SQL SERVER. So just apply the data source in the datagrid.

Conexao ca = new Conexao();
string sql = "";
sql += " Select ";
sql += " ROW_NUMBER() OVER(ORDER BY CausaDef) AS Legenda,";
sql += " CausaDef, Incidencia ";
sql += " From ";
sql += " Relat ";

ca.Conectar();
OleDbDataAdapter da = new OleDbDataAdapter(sql, ca.cx);
DataSet ds = new DataSet();
da.Fill(ds, "DetGraf");

object sumObject;
sumObject = ds.Tables["DetGraf"].Compute("Sum(Incidencia)", "");

ds.Tables["DetGraf"].Rows.Add("TOTAL", sumObject.ToString());

dgvDetGraf.DataSource = ds.Tables["DetGraf"];

ca.Desconectar();
    
30.05.2016 / 20:13