【问题标题】:displaying table data on datagridview在 datagridview 上显示表格数据
【发布时间】:2014-04-16 07:15:22
【问题描述】:

我正在使用 Windows 应用程序并显示从 sqlite 到 datagriview 的表数据,但我不明白为什么我的日期格式在显示期间会发生变化。

sqlite 日期格式DateTime 2012-02-20 16:42:10.000

datagridview 日期格式20/02/2012 16:42:10

我的代码

SQLiteConnection m_dbConnection;

m_dbConnection = new SQLiteConnection("Data source = F:/Explor/final test/WebMobility.db; Version=3;");

m_dbConnection.Open();

SQLiteCommand myCommand = new SQLiteCommand();
myCommand.Connection = m_dbConnection;


myCommand.CommandText = "select CompanyId,DateTime,description  from  VerbaliData";

DataTable data = new DataTable();
SQLiteDataAdapter myAdapter = new SQLiteDataAdapter(myCommand);

myAdapter.Fill(data);
dataGridView1.DataSource = data;
this.dataGridView1.Refresh();
if (dataGridView1.RowCount > 0)
{
    string value = "";
    DataGridViewRow dr = new DataGridViewRow();
    StreamWriter swOut = new StreamWriter("F:/Explor/final test/finaltest12.csv");

    //write header rows to csv
    for (int i = 0; i <= dataGridView1.Columns.Count - 1; i++)
    {
        if (i > 0)
        {
            swOut.Write(",");
        }
        swOut.Write(dataGridView1.Columns[i].HeaderText);
    }

    swOut.WriteLine();

    //write DataGridView rows to csv
    for (int j = 0; j <= dataGridView1.Rows.Count - 1; j++)
    {
        if (j > 0)
        {
            swOut.WriteLine();
        }

        dr = dataGridView1.Rows[j];

        for (int i = 0; i <= dataGridView1.Columns.Count - 1; i++)
        {
            if (i > 0)
            {
                swOut.Write(",");
            }

            value = dr.Cells[i].Value.ToString();
            //replace comma's with spaces
            value = value.Replace(',', ' ');
            //replace embedded newlines with spaces
            value = value.Replace(Environment.NewLine, " ");

            swOut.Write(value);
        }
    }
    swOut.Close();
}

m_dbConnection.Close();

【问题讨论】:

    标签: c# datagridview


    【解决方案1】:

    数据库始终以yyy-MM-dd 格式存储。 DatGrid 中的日期显示的格式基于您的机器日期格式。

    您可以通过以下示例看到这一点。查询您的数据库以获取当前日期,如下所示

    select FORMAT(GETDATE(),'dd/MM/yyy');
    

    结果将是2014-03-12 14:50:45.450

    你可以通过Format函数来改变它。

    select FORMAT(GETDATE(),'dd/MM/yyy');
    

    像下面这样更改您的查询将解决问题。

    select CompanyId, FORMAT(GETDATE(),'yyy-MM-dd hh:mm:ss'), description from  VerbaliData;
    

    【讨论】:

      【解决方案2】:

      这有两件事,SqlLite 保存的日期时间格式称为通用格式,它可以在所有应用程序中访问。 这有助于我们避免本地化问题。 sqlite 日期格式 DateTime 2012-02-20 16:42:10.000

      DataGrid 显示这一点是因为它选择了您的系统格式,即 DD/MM/YYYY,如果您需要以相同的格式显示它,您需要明确声明。 例如Date.ToUniversalTime() datagridview 日期格式 20/02/2012 16:42:10

      【讨论】:

      • 我已经更改了我电脑上的日期时间系统,非常感谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-01-07
      • 1970-01-01
      • 2011-07-31
      • 2016-10-12
      相关资源
      最近更新 更多