[英]Get Numeric Value from DataGridViewCell?
我正在嘗試從DataGridView
檢索數值。 到目前為止,我發現的唯一方法是將它們檢索為字符串並將其轉換為數字。
Convert.ToDouble(MyGrid.SelectedRows[0].Cells[0].Value.ToString());
必須有一個更簡單的方法。 該單元格最初是使用數字字段值從DataSet
填充的,但是由於DataGridViewCell
對象將其作為對象返回,因此我無法進行直接分配。 我一定在這里缺少一些簡單的東西。
謝謝。
實際上,我最近剛剛處理了這個問題,我認為TryParse
是關於健壯性的最佳選擇,但不要忘記檢查Cell中的null
是否為null
,否則TryParse
將會失敗並拋出錯誤。
double d = 0;
if(grid[col,row].Value != null)
double.TryParse(grid[col,row].Value.ToString(), out d);
我還建議避免直接轉換,除非您完全知道要轉換的類型,並且實際上在那里會有一個值,否則可能會在某個時候導致代碼錯誤。
使用DataGridViewCell
您可以將.Value
為您的已知類型。 以下是一個完整的示例,該示例顯示了DataTable
發生的這種情況(使用double)(如您的示例)。 此外, Convert.To{blah}(...)
和Convert.ChangeType(...)
可能會有所幫助。
using System.Data;
using System.Windows.Forms;
static class Program
{
static void Main()
{
Application.EnableVisualStyles();
DataTable table = new DataTable
{
Columns = {
{"Foo", typeof(double)},
{"Bar", typeof(string)}
},
Rows = {
{123.45, "abc"},
{678.90, "def"}
}
};
Form form = new Form();
DataGridView grid = new DataGridView {
Dock = DockStyle.Fill, DataSource = table};
form.Controls.Add(grid);
grid.CurrentCellChanged += delegate
{
form.Text = string.Format("{0}: {1}",
grid.CurrentCell.Value.GetType(),
grid.CurrentCell.Value);
if (grid.CurrentCell.Value is double)
{
double val = (double)grid.CurrentCell.Value;
form.Text += " is a double: " + val;
}
};
Application.Run(form);
}
}
DataGridViewCell
具有ValueType
屬性。 您可以用來直接將值轉換為該類型,而無需先將其轉換為字符串:
if(MyGrid.SelectedRows[0].Cells[0].ValueType!=null &&
MyGrid.SelectedRows[0].Cells[0].ValueType == Double)
return (Double)MyGrid.SelectedRows[0].Cells[0].Value;
您遇到什么錯誤? Convert.ToDouble
有一個帶對象的重載方法,因此您不需要ToString()
嗎? 除非您正在執行TryParse
?
由於DataGridViewCell.Value
是對象類型,因此您確實需要將其轉換為適當的類型, Double
或任何numeric
類型。 DataGridView
內容不是強類型的,因此您必須轉換從其單元格檢索的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.