我有一个Winforms datagridview,其中现有行不应该是可编辑的,但新行应该是。 所以我在网格上将ReadOnly属性设置为true,但之后我仍然看到新行但无法编辑它。 我如何结合这两个属性?
编辑:只是尝试将ReadOnly设置为true,但仍然无法编辑或添加新行。
conn = new SqlCeConnection();
conn.ConnectionString = connectionstring;
conn.Open();
daFacturen = new SqlCeDataAdapter("SELECT * FROM Factuur", conn);
daFacturen.Fill(dsKlantenBeheer, "tblFactuur");
daFactuurRegels = new SqlCeDataAdapter("SELECT * FROM Factuurregel", conn);
daFactuurRegels.Fill(dsKlantenBeheer, "tblFactuurregel");
// Relation between customers and orders
DataRelation relKlantFactuur;
DataColumn relKlantFactuurcolMaster;
DataColumn relKlantFactuurcolDetail;
relKlantFactuurcolMaster = dsKlantenBeheer.Tables["tblKlant"].Columns["ID"];
relKlantFactuurcolDetail = dsKlantenBeheer.Tables["tblFactuur"].Columns["KlantID"];
relKlantFactuur = new DataRelation("RelKlantFactuur", relKlantFactuurcolMaster, relKlantFactuurcolDetail);
dsKlantenBeheer.Relations.Add(relKlantFactuur);
DataRelation relFactFactregel;
DataColumn relFactFactregelcolMaster;
DataColumn relFactFactregelcolDetail;
relFactFactregelcolMaster = dsKlantenBeheer.Tables["tblFactuur"].Columns["ID"];
relFactFactregelcolDetail = dsKlantenBeheer.Tables["tblFactuurregel"].Columns["FactuurID"];
relFactFactregel = new DataRelation("relFactFactregel", relFactFactregelcolMaster, relFactFactregelcolDetail);
dsKlantenBeheer.Relations.Add(relFactFactregel);
DataViewManager dsView = dsKlantenBeheer.DefaultViewManager;
dsView.DataViewSettings["tblKlant"].RowFilter = "Status = 0 or Status is null";
dsView.DataViewSettings["tblKlant"].Sort = "Naam, Voornaam";
// Grid Databinding
dgvFacturen.DataSource = dsView;
dgvFacturen.DataMember = "tblKlant.relKlantFactuur";
dgvFacturen.ReadOnly = true;
dgvFacturen.allowUserToAddRows = true;
答案 0 :(得分:0)
仅为行/单元格设置ReadOnly
,而不是为整个网格设置:
var row = dataGridView1.Rows[0];
row.ReadOnly = true; //whole row can't be edited
或
var row = dataGridView1.Rows[0];
row.Cells[0].ReadOnly = true; //only first cell is not editable
当DataGridView
为ReadOnly
时,您无法编辑,添加,删除网格中的任何行/单元格。
答案 1 :(得分:0)
以下是我的解决方案,只需向CellBeginEdit
添加一些自定义代码,如下所示:
public bool Editable {get;set;}
int i;
private void dataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if(Editable) return;
if(i == e.RowIndex)
{
foreach (DataGridViewCell cell in dataGridView1.Rows[e.RowIndex].Cells)
{
if (cell.Value == null)
{
return;
}
}
e.Cancel = true;
}
else if (dataGridView1.Rows.Count - 1 != e.RowIndex)
{
e.Cancel = true;
}
else i = e.RowIndex;
}
上面的代码会阻止您在输入该行中所有单元格的所有值后重新编辑新行。如果您希望允许用户在提交所有值后编辑该新行,则代码似乎更简单:
private void dataGridView_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
{
if(Editable) return;
if(e.RowIndex < dataGridView.Rows.Count - 2)
{
e.Cancel = true;
}
}
我测试过并且像魅力一样工作。我想你的新行将为所有单元格输入新值。