我不知道它不工作的原因,但據我所知,它必須處理我綁定的數據的方式。如果您使用dataGridView1.DataSource = GetDataSource();
,那麼它在我的測試中不起作用。我讀過一次關於自動綁定的一些缺點,但我找不到它。這是可用的代碼。在用戶單擊相應行中的按鈕Edit
後,行僅在EditMode中。我會稍後回來 - 讓我知道你是否需要更多的指針。
public partial class Form1 : Form
{
int rowIndexOfEditableRow = -1;
public Form1() {
InitializeComponent();
CreateDataGridView(dataGridView1);
SetExistingDataGridViewRowsReadOnly();
this.dataGridView1.Columns.Add(GetBtnColumn());
}
private void SetExistingDataGridViewRowsReadOnly() {
DataGridViewRowCollection rows = this.dataGridView1.Rows;
foreach (DataGridViewRow row in rows) {
row.ReadOnly = true;
}
}
看來,電網必須手動填寫 - 至少這種方式只讀的變化工作
public void CreateDataGridView(DataGridView dgv)
{
dgv.ColumnCount = 3;
dgv.Columns[0].Name = "Id";
dgv.Columns[1].Name = "Lastname";
dgv.Columns[2].Name = "City";
dgv.BackgroundColor = Color.Gray;
AddRowsToDataGridView(dgv);
}
private void AddRowsToDataGridView(DataGridView dgv)
{
string[] row1 = new string[]{"1", "Muller", "Seattle"};
string[] row2 = new string[]{"2", "Arkan", "Austin"};
string[] row3 = new string[]{"3", "Cooper", "New York"};
object[] rows = new object[] { row1, row2, row3 };
foreach (string[] rowArray in rows)
{
dgv.Rows.Add(rowArray);
}
}
Helper方法與按鈕
public DataGridViewButtonColumn GetBtnColumn()
{
DataGridViewButtonColumn btnColumn = new DataGridViewButtonColumn();
btnColumn.HeaderText = "Edit";
btnColumn.Text = "Edit";
btnColumn.UseColumnTextForButtonValue = true;
return btnColumn;
}
事件創建列處理程序檢查用戶是否點擊了編輯按鈕。在這種情況下,當前行將被設置爲ReadOnly = false
。這允許用戶編輯該行。爲了強調它,我改變了該行的背景顏色。
private void DataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
int colIndex = e.ColumnIndex;
int rowIndex = e.RowIndex;
Type cellType = dataGridView1.Columns[colIndex].CellType;
if (cellType == typeof(DataGridViewButtonCell))
{
dataGridView1.Rows[rowIndex].ReadOnly = false;
dataGridView1.Rows[rowIndex].DefaultCellStyle.BackColor = Color.GreenYellow;
this.rowIndexOfEditableRow = rowIndex;
label1.Text = rowIndexOfEditableRow.ToString() + " " + colIndex.ToString();
}
}
如果RowLeave,事件觸發的風格是復位和全球parmeter哪一行是可編輯設置爲初始值
private void DataGridView1_RowLeave(object sender, DataGridViewCellEventArgs e)
{
int rowIndex = e.RowIndex;
dataGridView1.Rows[rowIndex].ReadOnly = true;
dataGridView1.Rows[rowIndex].DefaultCellStyle.BackColor = Color.White;
this.rowIndexOfEditableRow = -1;
}
}
上面的代碼包含了所有(除設計文件)您需要創建此演示:
您確定事件觸發嗎?如果該行是隻讀的,我不確定您可以單擊該按鈕。 – Sebi
哦,你說得對。我想阻止所有單元格,以便人們無法編輯數據,除非必須單擊要編輯的行上的按鈕,然後該行才能被解除阻止。我怎樣才能做到這一點? –
這似乎很難。您可以嘗試處理Grid的Click事件。然後你必須使用GridHitInfo來知道光標的位置。如果位置在按鈕單元格的矩形中,則激活該行。它有點骯髒,因爲你假的按鈕或多或少,但這應該是工作,但我今天不能嘗試它抱歉。 – Sebi