[英]How to add new row to datagridview only after specific cells of the row above are filled?
我正在使用C#(.NET 4.0)開發桌面應用程序。 我有一個datagridview填充自定義對象,通過自定義(它繼承BindingList)BindingList(添加排序功能)。 我使用cellValidating事件來正確地增加第一列(ID)並驗證輸入到其他單元格。
問題是當我到達新行/最后一行並在一個單元格中輸入內容(我甚至可以在離開單元格之前刪除所有輸入)時,datagridview會自動將此行添加到綁定列表並在下面創建一個新行。 我希望只在正確填充上面的行(上一個新行)時才添加最后一個/新行。
例
ID NAME PRICE ...
1 Beer 2.6
2 Cheese 3.3
_ _______ ____ <- empty row
現在,如果我單擊(輸入),新行ID將自動設置為3,如果我將“點擊”保留為“啤酒”單元格,則新行ID為空,所有默認值均為空(這是它應該和工作的方式)。 問題是如果單擊/輸入新行並輸入名稱的內容(即使我在離開單元格之前刪除了內容),也會在此行下方添加一個新行,即新行。 因此,此行被添加到BindingList並且不完整,在正確填充所有必需單元格(例如價格)之前不應添加該行。
我不知道該怎么做。 請幫幫我,我是C#的新手。
謝謝你的時間和答案。
您必須在檢查特定條件( 驗證規則 )后處理RowValidating
事件並取消對事件的處理。 然后,當前正在輸入的行將不會提交到DataGridView,也不會添加新行。
例如:
if (dgv[0, e.RowIndex].Value == DBNull.Value)
{
dgv.Rows[e.RowIndex].ErrorText = "You must enter a value for this field!";
// Tell the DataGridView not to accept this row
e.Cancel = true;
}
如果您正在開發一個Windows應用程序並具有文本框以從用戶獲取輸入以更新到DataGridView,您可以在C#中執行此操作,請考慮以下事項:
if(txtNAME.Text.Trim()!=String.Empty&&txtPRICE.Text.Trim()!=String.Empty)
{
MessageBox.Show("Invalid type of input","Alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
else
{
SqlConnection _sqlconnectionOne=new SqlConnection(*DatabaseConnectionString*);
SqlCommand _sqlcommandOne=new SqlCommand();
_sqlcommandOne.CommandType=CommandType.Text;
_sqlcommandOne.CommandText="*INSERTStatement*";
_sqlcommandOne.Connection=_sqlconnectionOne;
_sqlcommandOne.ExecuteNonQuery();
SqlConnection _sqlconnectionSecond=new SqlConnection(*DatabaseConnectionString*);
SqlCommand _sqlcommandSecond=new SqlCommand();
_sqlcommandSecond.CommandType=CommandType.Text;
_sqlcommandSecond.CommandText="*SELECT*Statement*";
_sqlcommandSecond.Connection=_sqlconnectionSecond;
SqlDataAdapter _sqldataadapter=new SqlDataAdapter(_sqlcommandSecond);
DataTable _datatable=new DataTable();
_sqldataadapter.fill(_datatable);
*DataGridViewName*.DataSource=_datatable;
}
或者你可以使用文本框的離開事件,但有時會變得有點喧囂。 建議隨時歡迎!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.