簡體   English   中英

從DataGridViewCell獲取數值?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM