简体   繁体   中英

Set DataGridView cell value and add a new row

I have a DataGridView with two columns. When a cell in the first column is clicked, an OpenFileDialog is shown and when I select a file, the cell in the second column value is set to the selected file name. Here is the code:

private void dataGridView1_CellContentClick(
    object sender, DataGridViewCellEventArgs e)
{
    if (e.ColumnIndex == 0)
    {
        SelectFile(e.RowIndex);
    }
}

private void SelectFile(int rowIndex)
{
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        dataGridView1.Rows[rowIndex].Cells[1].Value =
            openFileDialog.FileName;
    }
}

This works, but I would like a new row to be added when the cell value is set. This happens when I edit the cell manually, the row gets in 'edit' state and a new row is added below. I would like the same to happen when I set the cell value programmatically.

[edit]

When my form is first shown the DataGridView is empty and the only row is shown is the one with (* sign - IsNewRow is true). When I manually edit a cell in that row it goes into edit state (pencil sign) and a new empty row is added. This doesn't happen when I use the above code. The row remains as IsNewRow (* sign) and a new row is not added.

在此处输入图像描述在此处输入图像描述

I ran into the same problem, too. I did something like the following, it just works..! (.Net framework 4.5)

// Set value for some cell, assuming rowIndex refer to the new row.
dateGridView1.Rows[rowIndex].Cells[1].Value = "Some Value";

// Then simply do this:
dataGridView1.BeginEdit(true);
dataGridView1.EndEdit();

With this code you can do what you want to do. I Used it for the same reason:

myGrid.NotifyCurrentCellDirty(true);

Source of this answer: Make new row dirty programmatically and insert a new row after it in DataGridView

I ran into the same problem. Didn't figure out a more elegant solution but thought it might be helpful to provide some code:

//...
    DialogResult dr = ofd.ShowDialog();
    if (dr == DialogResult.OK)
        {
            DataGridViewRow curRow = cell.DataGridView.Rows[cell.RowIndex];
            // check if the current row is the new row
            if (curRow.IsNewRow)
            {
                // if yes, add a new one
                int newRowIdx = cell.DataGridView.Rows.Add();
                DataGridViewRow newRow = cell.DataGridView.Rows[newRowIdx];
                DataGridViewCell newCell = newRow.Cells[cell.ColumnIndex];
                // check if the new one is _not_ the new row (this is the unexpected behavior mentioned in the questions comments)
                if (!newRow.IsNewRow)
                    newCell.Value = ofd.FileName;
                else if (!curRow.IsNewRow)
                    cell.Value = ofd.FileName;
            }
            else {
                cell.Value = ofd.FileName;
            }
        }

I ran into this and solved it in a different way.

Basically the user clicks a button on the DataGridView , it opens a dialog which asks questions, then fills the row out. Just for the fun of it, I fixed it by using SendKeys to get the row in edit mode instead of new mode. You don't have to use SendKeys to fill out the entire row, just one cell is enough to make it work.

Two important things to note. First the datagridview needs to have multiselect off, or you need to unselect the current cell(s). Second, you need the defaultvaluesneeded event to work and fill the grid with sane data.

myRow.Cells("dgvStockNumber").Selected = True
OrderDetailDataGridView.BeginEdit(True)
SendKeys.Send("{Backspace}")
SendKeys.Send(scp.MyStockCard.StockNumber)
Application.DoEvents()
OrderDetailDataGridView.EndEdit()
myRow.Cells("dgvChooseStockCard").Selected = True
OrderDetailDataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit)

There are better ways to go about this, but this is easy lol.

If it's on load you will need to add the new row first, then to give its cell a value do something like this.

When I was trying to fill certain columns of a Datagrid with certain columns of some Datatable and retrieving its data from a SQL database, I used this:

       if (dtbl.Rows.Count > 0)
        {
            for (int i = 0; i < dtbl.Rows.Count; i++)
            {
                    // adding a row each time it loops in and find a row in the dtbl
                    dataGridView1.Rows.Add();

                    dataGridView1.Rows[i].Cells[0].Value = dtbl.Rows[i][0].ToString();
                    dataGridView1.Rows[i].Cells[1].Value = dtbl.Rows[i][1].ToString();
                    dataGridView1.Rows[i].Cells[2].Value = dtbl.Rows[i][2].ToString();
            }
            dataGridView1.ReadOnly = true;
            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
        }  

I searched for the solution how I can insert a new row and How to set the individual values of the cells inside it like Excel. I solved with following code:

dataGridView1.ReadOnly = false; //Before you modify it, it should be set to false!

dataGridView1.Rows.Add(); //This inserts first row, index is "0"
dataGridView1.Rows[0].Cells[0].Value = "this is 0,0!"; //This line will set the right hand string to the very first cell of your datagridview.

Note: 1. Previously I have designed the columns in design mode. 2. I have set the row header visibility to false from property of the datagridview.

Hope this might help you.

It's not real clear what you're trying to do, but you can add new rows to a DataGridView like this:

dataGridView1.Rows.Add()

the.Add() method is overloaded, so check which Add method is the one you want in visual studio.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM