Adding data to an existing gridview

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Normann
    New Member
    • Jan 2007
    • 17

    Adding data to an existing gridview

    I am trying to add data to an existing gridview, the gridview already has defined columns and I need to add data to these columns.

    However when I use gridview.dataso urce, it just adds new columns to the gridview. It is properly not that hard to do this, but I have been hammering my head on this problem for the last three days and I haven’t been able to find any help on Google.

    I have added the code I have already made and it works ok, it just adds new columns instead of putting the data in the existing columns.

    Code:
    private void GridViewFunktion()
            {
    
                DataColumn colOrigName = new DataColumn("Original_Name");
                DataColumn colNr = new DataColumn("Nr");
                DataColumn colSystem_Hop = new DataColumn("System_Hop");
                DataColumn colType = new DataColumn("Type");
    
    
                myTable.Columns.Add(colOrigName);
                myTable.Columns.Add(colNr);
                myTable.Columns.Add(colSystem_Hop);
                myTable.Columns.Add(colType);
    
                varStringedt = OtherFunktions.VARSTRINGEDT;
    
                for (int i = 0; i < varStringedt.Length; i++)
                {
                    DataRow myRow;
                    myRow = myTable.NewRow();
                    myRow["Original_Name"] = varStringedt[i];
    
    
                    myTable.Rows.Add(myRow);
                }
    
                ReMk1_SE_dataGridView.DataSource = myTable;
            }
  • GaryTexmo
    Recognized Expert Top Contributor
    • Jul 2009
    • 1501

    #2
    Just because two DataColumn objects have the same text name doesn't mean they're the same object. You're actually creating 3 brand new columns and putting them into myTable, which you then hook to your DataGridViewobj ect.

    Also, if you call the above function more than once you're actually going to get more copies of your columns, since you're creating new DataColumn objects every single time.

    I'd suggest having the columns be completely defined by the DataTable and have DataGridView empty... or build the columns for the DataTable based on what's in the DataGridView, then clear the DataGridView columns before you set it's DataSource

    Does that make any sense or help you at all? I changed my thought process a few times in there so I realize I may be rambling a bit.

    Comment

    Working...