2017-08-28 133 views
0

我有一個網格視圖,我試圖插入一個新的值。在進行插入之前,需要檢查輸入的值是否已經存在於DB中(不能重複)。 需要檢查重複的列的類型是varchar,它可以接受字符串中的最大字符(它可以有空格,也可以有其他特殊字符 - 它基本上是一個句子)。 例如插入特定的與作業相關的影響:(例如,對客戶或客戶服務的影響) 由於聲明爲varchar(max),因此我們無法在SQL Server中使此列唯一。 我們可以從C#執行一個像這樣的大字符串檢查嗎?在C#中,我們可以檢查是否輸入重複值

+0

您可以在插入之前執行'SELECT COUNT(*)FROM TheTable WHERE TheField = @ MyUniqueValue'並檢查是否得到結果> 0。問題是'VARCHAR(MAX)不能被索引,所以它可能會很慢 –

+0

我早些時候試過這種方法來獲得行數。但即使輸入的匹配數總是'0',因此它插入記錄。 – Van

+0

這聽起來不合適。你能告訴我們你使用的代碼嗎? –

回答

0

主要概念如下:

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 
    } 
相關問題