schwall
schwall

Reputation: 5

Data from another class cannot be put to a datagridview

Good day. I have passed a data variable from one class to another to put into a datagridview in the main form. I put some message boxes in each case to know that it accesses the said function and that the data is clearly passed. But when I run the program. The table doesn't put the data inside it.

Here is the code when I pass the data

if (txtCode1.ElementAt(intCtr + 1).Equals(val4)) {
   MessageBox.Show("Lol");
   Compilourdes_GUI cmp = new Compilourdes_GUI();
   cmp.AddtotblLexeme(val2, val2);
   break;
}

And here is the code of AddtotblLexeme

public void AddtotblLexeme(string lexeme, string token) {
   MessageBox.Show(lexeme+" "+token);
   tblLexeme.Rows.Add(lexeme , token); //adding tokens and lexeme to the table
}

Code where I made the DataTable

private void Start()
{
    tbl1.AutoGenerateColumns = true;
    tbl1.DataSource = null;
    tbl1.Rows.Clear();

    InitTable();

    string txtCode1 = txtCode.Text;
    LexicalAnalyzer lex = new LexicalAnalyzer(txtCode1);
    lex.StartLex();
    tbl1.DataSource = tblLexeme;
}

public void InitTable()
{
    tblLexeme = new DataTable();
    tblLexeme.Columns.Add("Lexeme", typeof(string));
    tblLexeme.Columns.Add("Token", typeof(string));
}

DataTable tblLexeme = new DataTable();

Here is the image of the output the "TEST" word/s should be inside the table. the "TEST" word/s should be inside the table, but as you can see, it didn't get put in.

Upvotes: 0

Views: 75

Answers (1)

Jonathan Willcock
Jonathan Willcock

Reputation: 5235

Ok I think I understand your problem. If you added the columns directly in the designer, my guess is that you added unbound columns. If so, then the DataGridView cannot match up the row you are adding to the rows in the table. To fix this, delete the columns from the DatagridView. Then make sure that your DataGridView has property AutoGenerateColumns = true, before setting DataSource = tblLexeme. Now two things happen automatically: firstly the DataGridView picks up the columns from your DataTable; and secondly, when adding a new row to the DataTable, it should show automatically in the DataGridView.

In AddtotblLexeme, for testing purposes, can you please add, in place of your Rows.Add():

DataRow nR = tblLexeme.NewRow();
nR[0] = lexeme;
nR[1] = token;
tblLexeme.Rows.Add(nR);

Then in debugger check that nR does have an ItemArray with 2 columns.

Upvotes: 1

Related Questions