主要概念如下:
private void dataGridView1_CellValueChanged_1(object sender, DataGridViewCellEventArgs e)
{
int columnToCheck = 0;//The index of the property/field/column you want to check
if (e.ColumnIndex == columnToCheck)
{
using (var DB = new DataContext())
{
if (DB.YourTable.Where(v => v.id == dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()).Count > 0)
{
dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
MessageBox.Show("This key already exists");
//Return the error message to your javascript in asp.net here
}
}
}
}
在網站但是,你必須做出一個Ajax調用,所以兩者的DataTable你使用,發現它的事件這將類似的dataGridView的CellValueChanged事件。如果您沒有這樣做,請嘗試在其HTML元素定義中添加onchanged =「」標記,例如<table class="table" id="tab" onchanged="eventfunction(this)"></table>
並在你的JavaScript,處理像調用以下:
function eventfunction(element)
{
//Use an ajax call to your controller from here
var id = document.getElementById(element.id).innerText; //or however you can obtain the active cells' value
$.ajax({
url: "/api/ControllerName/ActionName",
method: "POST",
data: id,
success: function (response)
{
//Handle the return call here
},
error: function (response)
{
//Or here if you return an error message
}
});
}
或者你也可以使用jQuery的事件處理是這樣的:
$("#tab").on("onchange", function()
{
//Your code here
});
你控制器可以是這樣的:
[HttpPost]
public Customer GetCustomer(string id)
{
//LINQ Where validation here
}
您可以在插入之前執行'SELECT COUNT(*)FROM TheTable WHERE TheField = @ MyUniqueValue'並檢查是否得到結果> 0。問題是'VARCHAR(MAX)不能被索引,所以它可能會很慢 –
我早些時候試過這種方法來獲得行數。但即使輸入的匹配數總是'0',因此它插入記錄。 – Van
這聽起來不合適。你能告訴我們你使用的代碼嗎? –