防止datagridview单元格创建新行.
问题描述:
我有一个datagridview,可用来从用户那里获取输入.
问题是,每当我开始在任何单元格中输入值时,都会自动添加新行.我仅在当前行的最后一个单元格完成编辑后才需要添加新行.
另外,我需要设置可添加的新行数的限制.
谢谢.
Hi,
I have a datagridview which I use to get input from user.
The problem is that whenever I start inputting the values in any of the cells, a new row is automatically added. I need a new row to be added only when the last cell in the current row has finished with editing.
Also I need to set limit on how many new rows can be added.
Thank you.
答
将datagridview的属性-AllowUserToAddRows设置为False
点击按钮添加行.
按钮单击事件参数
Set the property of datagridview - AllowUserToAddRows as False
Give a button to add rows.
button click event argument
{
datatgridview.Rows.Add();
}
if(datagirdview.Rows.Count < n (your limit))
{
Disable the Button (add row)
}
谢谢
Saranya1388
Thanks
Saranya1388
看看这个,可能会对您有所帮助.
注意:VB中的代码,请尝试更改C#
Look at this, it may help you.
Note: Code in VB, Try to change C#
Set DataGridView1-AllowUserToAddRows as False
Private Sub DataGridView1_CellContentClick1(ByVal sender As Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
If DataGridView1.Rows.Count > 0 Then
If e.RowIndex >= 0 Then
temprowid = e.RowIndex
End If
End If
End Sub
Private Sub DataGridView1_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles DataGridView1.KeyPress
//if (e.KeyChar == (char)Keys.Tab) //--From CSharp
If e.KeyChar.Equals(Keys.Tab) Then //--Check This is Correct or Not
If temprowid >= 0 Then
If (DataGridView1.Columns(DataGridView1.CurrentCell.ColumnIndex()).HeaderText.Equals("LastCellName")) Then
BindingSource1.AddNew()
End If
End If
End If
End Sub
将DataGridView1-AllowUserToAddRows设置为错误
Set DataGridView1-AllowUserToAddRows as False
int temprowid=0;
private void DataGridView1_CellContentClick1(object sender, DataGridViewCellCancelEventArgs e)
{
if(DataGridView1.Rows.Count > 0 )
{
if( e.RowIndex >= 0)
temprowid = e.RowIndex;
}
}
private void DataGridView1_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Tab)
{
if(temprowid >= 0)
{
if(DataGridView1.Columns[DataGridView1.CurrentCell.ColumnIndex].HeaderText.Equals("LastCellName"))
FillGrid(1);
}
}
}
Private Void FillGrid(int RowCount)
{
foreach (DataGridViewRow r in DataGridView1.Rows)
{
DataGridView1.Rows.Remove(r);
}
DataGridView1.DataSource = null;
if (DataGridView1.Columns.Count > 0)
{
DataGridView1.Columns.Clear();
}
DataTable dt=new DataTable()
dt=dc.GetDataTable("Select Statement"); //--Returns DataTable
if(Rowount > 0)
{
For(int i=0;i<RowCount;i++)
{
DataRow dr = dt.NewRow();
dt.Rows.Add(dr);
}
}
DataGridView1.DataSource=dt;
}