سؤال

I am coming across something strange or maybe it is the way it works and its just my lack of understand of how the datagridview works. I am dynamically adding a column when I click on a button

    private void btnAssign_Click(object sender, EventArgs e)
    {
        if (!gvData.Columns.Contains("DepartmentId"))
        {
            DataGridViewTextBoxCell cell = new DataGridViewTextBoxCell();
            DataGridViewColumn dc = new DataGridViewColumn();
            dc = new DataGridViewTextBoxColumn();
            dc.HeaderText = "DepartmentId";
            dc.Name = "DepartmentId";
            dc.CellTemplate = cell;
            gvData.Columns.Add(dc);
        }
        foreach(DataGridViewRow row in gvData.SelectedRows)
        {
            row.Cells["DepartmentId"].Value = getSelectedValues(clbDept);
        }
    }

first it checks if the DepartmentId column is in the datagridview (dgv). If not then I create a new Datagridviewtextboxcolumn and sets the appropriate settings. Then adds values to the cells. SO far so good... this where is does weird things... when I sort another column, the data in the 'DepartmentId' column disappears. Data disappears in the columns that I dynamically create. Do i have to use a save method or something?

هل كانت مفيدة؟

المحلول

Instead of adding data directly to datagridview you need to add column to datasource and reassign the datasource to datagridview. This will resolve your sorting issue.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top