2011-06-15 14 views
18

Mam datatable z jedną kolumnąName "CustomerID" z Integer DataType. Dynamicznie chcę dodać wiersze do DataTable. Za to, że stworzył jeden obiekt DataRow jak:Przypisanie wartości Null do kolumny Integer w DataTable

DataTable dt = new DataTable(); 
    DataRow DR = dt.NewRow(); 
    DR["CustomerID"] = Convert.ToInt32(TextBox1.Text); 

Ale jeśli TextBox zawiera pusty ciąg, zgłasza błąd. W takim przypadku chcę przypisać wartość Null do identyfikatora klienta. Jak to zrobić?

+0

@Marc dlaczego nie ty polecić mu coś zamiast używania DataTable? – mqpasta

+1

@Marc: Tak. Iam za pomocą DataTable. – thevan

Odpowiedz

25

null/pusty ciąg jest w złym formacie; trzeba by wykryć, że scenariusz i kompensować:

DR["CustomerID"] = string.IsNullOrWhiteSpace(text) 
     ? DBNull.Value : (object)Convert.ToInt32(text); 
4
DR["CustomerID"] = !string.IsNullOrEmpty(TextBox1.Text) 
        ? Convert.ToInt32(TextBox1.Text) 
        : DBNull.Value; 

Ale należy sprawdzić również, że wartość jest poprawną liczbą całkowitą:

int value; 
if(int.TryParse(TextBox1.Text, out value)) 
{ 
    DR["CustomerID"] = value; 
} 
else 
{ 
    DR["CustomerID"] = DBNull.Value; 
} 
1

Można użyć DBNull.

DR["CustomerID"] = (TextBox.Text.Length == 0) ? Convert.ToInt32(TextBox1.Text) : DBNull.Value; 
1
if (TextBox1.Text.Trim() == String.Empty) 
    { 
     DR["CustomerID"] = null; 
    } 
    else 
    { 
     DR["CustomerID"] = Convert.ToInt32(TextBox1.Text); 
    } 
2

można zrobić to tak:

DR["CustomerID"] = string.IsNullOrEmpty(TextBox1.Text) ? 
    null : Convert.ToInt32(TextBox1.Text); 
2

Przede wszystkim, oczywiście, pole musi być ustawiony jako pustych w DB.

A następnie ustawić go do DBNull.Value

1
DataTable dt = new DataTable(); 
DataRow DR = dt.NewRow(); 

if (String.IsNullOrEmpty(TextBox1.Text)) 
    DR["CustomerID"] = DBNull.Value; 
else 
    DR["CustomerID"] = Convert.ToInt32(TextBox1.Text); 
1

Jeśli zadeklarujesz zmienną Integer jako int? jest automatycznie zapakowany w kompilator C# i możesz przypisać wartość zerową do tej zmiennej. Na przykład:

int? custID = null; 

Mam nadzieję, że pomaga

2

Trzeba sprawdzić najpierw

if (TextBox1.Text.Length > 0) 
{ 
    DR["CustomerID"] = Convert.ToInt32(TextBox1.Text); ; 
} 
else 
{ 
    DR["CustomerID"] = null; 
} 
2
Int32 Temp = 0; 
if !(Int32.TryParse(TextBox1.Text,Temp)) 
    DR["CustomerID"] = DBNull.Value 
else 
    DR["CustomerID"] = Temp 
1

Kiedy null nie może być wprowadzony do DR["CustomerID"], można użyć (int?)null zamiast tak:

DR["CustomerID"] = string.IsNullOrEmpty(TextBox1.Text) ? 
(int?) null : Convert.ToInt32(TextBox1.Text); 
Powiązane problemy