2013-07-05 32 views
0

我知道如何設置datagridview的特定列中的行的最大長度,但是如果輸入更短的長度的字符串,它每次都會更改。我想要設置長度使得最大長度一開始只設置一次,這基本上是字符串的長度。第一次設置特定列的行的最大長度

例如,如果該字符串的長度爲5在如此,即使我改變字符串的文字和長度被改變爲3的最大長度的開始保持5.

這是我的代碼。

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
    { 
     //check if currently selected cell is cell you want 
     if (dataGridView1.CurrentCell == null || dataGridView1.CurrentCell.ColumnIndex != 2) 
     { 
      return; 
     } 

     if (e.Control is TextBox && !(Convert.ToBoolean(this.dataGridView1.CurrentRow.Cells[8].Value.ToString()))) 
     { 
      ((TextBox)e.Control).MaxLength = Convert.ToInt16(this.dataGridView1.CurrentRow.Cells[3].Value.ToString()); 
     } 
    } 
+0

創建一個布爾變量VAR isFirstTime =真正;那麼在你的代碼中檢查if(isFirstTime)並設置你的最大長度並將此參數改爲false。 – Ehsan

回答

1

創建一個布爾變量作爲

var isFirstTime =true; 

那麼你的代碼檢查,如果(isFirstTime)內,並設置你的最大長度,這個參數更改爲false。

private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e) 
{ 
    //check if currently selected cell is cell you want 
    if (dataGridView1.CurrentCell == null || dataGridView1.CurrentCell.ColumnIndex != 2) 
    { 
     return; 
    } 

    if (e.Control is TextBox && !(Convert.ToBoolean(this.dataGridView1.CurrentRow.Cells[8].Value.ToString()))) 
    { 
     if(isFirstTime) 
     { 
     ((TextBox)e.Control).MaxLength = Convert.ToInt16(this.dataGridView1.CurrentRow.Cells[3].Value.ToString()); 
      isFirstTime=false; 
    } 
    } 
} 
+0

總是有不同的方式來完成同一個任務,但是這個解決方案比我提交的更好,因爲它更清晰,更重要的是它會減少操作的次數(1而不是2)好的工作 – user2497624

0

在你的代碼中發生了什麼是你定義了字符串長度的最大長度基準。在這種情況下,您需要將if語句添加到代碼中。如果要encompassethe第二,如果你的代碼,並在這裏首先是它的條件

if ((TextBox)e.Control).MaxLength >= Convert.ToInt16(this.dataGridView1.CurrentRow.Cells[3].Value.ToString()) 

該代碼將阻止你增加你的最大長度的大小。 如果這是它的代碼,第二個if將嵌套在第二個if中。

if ((TextBox)e.Control).MaxLength < Convert.ToInt16(this.dataGridView1.CurrentRow.Cells[3].Value.ToString()) 

,如果這是真的,你什麼也不做,你申請的最大長度定義你有

((TextBox)e.Control).MaxLength = Convert.ToInt16(this.dataGridView1.CurrentRow.Cells[3].Value.ToString()); 

這將防止最大長度的縮短

+0

問題是,我已經將所有字符串的最大長度設置爲130,但是有一些字符串的最大長度與開始時的字符串長度相同:( – soldiershin

+0

對不起,我很困惑,所以你想要你的單元格的最大長度爲130,但有些單元格的最大值必須小於這個值。 無論如何,看看Elhsan的答案,它比我的好,它可以讓你在開始之前定義一個最大值( 130),然後調整你的最大值到你輸入的第一個字符串的長度 – user2497624