C#将DataTable绑定到现有的DataGridView列定义 [英] C# Bind DataTable to Existing DataGridView Column Definitions

查看:346
本文介绍了C#将DataTable绑定到现有的DataGridView列定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力使用NullReferenceException,希望有人能够指出我正确的方向。我正在尝试创建和填充DataTable,然后在DataGridView控件中显示结果。基本代码如下,在调用新的UpdateResults_Delegate的时候,执行会停止NullReferenceException。奇怪的是,我可以跟踪entries.Rows.Count成功之前,我从QueryEventEntries返回,所以我可以至少显示1)条目不是一个空引用,和2)DataTable包含数据行。我知道我必须做错事,但我只是不知道什么。

  private void UpdateResults(DataTable entries) 
{
dataGridView.DataSource = entries;
}

private void button_Click(object sender,EventArgs e)
{
PerformQuery();
}

private void PerformQuery()
{
DateTime start = new DateTime(dateTimePicker1.Value.Year,
dateTimePicker1.Value.Month,
dateTimePicker1.Value.Day,
0,0,0);

DateTime stop = new DateTime(dateTimePicker2.Value.Year,
dateTimePicker2.Value.Month,
dateTimePicker2.Value.Day,
0,0,0) ;

DataTable entries = QueryEventEntries(start,stop);
UpdateResults(entries);
}

private DataTable QueryEventEntries(DateTime start,DateTime stop)
{
DataTable entries = new DataTable();
entries.Columns.AddRange(new DataColumn [] {
new DataColumn(event_type,typeof(Int32)),
new DataColumn(event_time,typeof(DateTime)),
new DataColumn(event_detail,typeof(String))});

使用(SqlConnection conn = new SqlConnection(DSN))
{
using(SqlDataAdapter adapter = new SqlDataAdapter(
SELECT event_type,event_time,event_detail FROM event_log +
WHERE event_time> = @start AND event_time< = @stop,
conn))
{
adapter.SelectCommand.Parameters.AddRange(new Object [] {
new SqlParameter(@ start,start),
new SqlParameter(@ stop,stop)});
adapter.Fill(entries);
}
}
返回条目;
}






更新



我想总结并提供我从这里讨论中学到的一些其他信息,并从最初发布这个问题开始调试工作。 >

我正在重构从数据库中检索记录的旧代码,将这些记录作为数组收集,然后在数组中迭代,逐行填充DataGridView。线程最初被实现为在不必要的循环期间补偿并保持UI响应。我已经剥离了Thread / Invoke;现在所有的事情都发生在相同的执行线程上(谢谢, Sam )。



尝试用DataTable替换缓慢而笨拙的方法,我可以使用DataAdapter来填充DataGridView,并通过DataSource属性(上面的代码更新)分配给DataGridView。



我已经遍历了DataTable的行,以便在将它分配给DataGridView的DataSource之前验证该表包含预期的数据。

  foreach(entry.Rows中的DataRow行)
{
System.Diagnostics.Trace.WriteLine(
String.Format({0} {1} {2},行[0],行[1],行[2]));
}

DataGridView的一列是一个自定义的DataGridViewColumn,用于对event_type值进行风格化。我很抱歉,我没有在原来的帖子中提到这个,但我并不知道这对我的问题很重要。我已将此列临时转换为标准的DataGridViewTextBoxColumn控件,并且不再经历异常。



DataTable中的字段将附加到已预先填写的字段列表中在DataGridView的设计视图中指定。记录的值正在这些附加字段中填充。当运行时间尝试渲染单元格时,提供了一个空值(因为应该被渲染的值是这样的,所以有几列)。



鉴于此,我正在重新标注和重新标记问题。如果有经验的人可以指导我如何将DataTable绑定到DataGridView的现有列定义,我仍然会感激,

解决方案

您需要确保每列的 DataPropertyName 属性设置为相应的名称 DataColumn s ColumnName



您可能还需要设置 DataGridView AutoGenerateColumns 属性为 false



我找到了解决方案 here


I've been struggling with a NullReferenceException and hope someone here will be able to point me in the right direction. I'm trying to create and populate a DataTable and then show the results in a DataGridView control. The basic code follows, and Execution stops with a NullReferenceException at the point where I invoke the new UpdateResults_Delegate. Oddly enough, I can trace entries.Rows.Count successfully before I return it from QueryEventEntries, so I can at least show 1) entries is not a null reference, and 2) the DataTable contains rows of data. I know I have to be doing something wrong, but I just don't know what.

private void UpdateResults(DataTable entries)
{
    dataGridView.DataSource = entries;
}

private void button_Click(object sender, EventArgs e)
{
    PerformQuery();
}

private void PerformQuery()
{
    DateTime start = new DateTime(dateTimePicker1.Value.Year,
                                  dateTimePicker1.Value.Month,
                                  dateTimePicker1.Value.Day,
                                  0, 0, 0);

    DateTime stop  = new DateTime(dateTimePicker2.Value.Year,
                                  dateTimePicker2.Value.Month,
                                  dateTimePicker2.Value.Day,
                                  0, 0, 0);

    DataTable entries = QueryEventEntries(start, stop);
    UpdateResults(entries);
}

private DataTable QueryEventEntries(DateTime start, DateTime stop)
{
    DataTable entries = new DataTable();
    entries.Columns.AddRange(new DataColumn[] {
        new DataColumn("event_type", typeof(Int32)),
        new DataColumn("event_time", typeof(DateTime)),
        new DataColumn("event_detail", typeof(String))});

    using (SqlConnection conn = new SqlConnection(DSN))
    {
        using (SqlDataAdapter adapter = new SqlDataAdapter(
            "SELECT event_type, event_time, event_detail FROM event_log " +
            "WHERE event_time >= @start AND event_time <= @stop",
            conn))
        {
            adapter.SelectCommand.Parameters.AddRange(new Object[] {
                new SqlParameter("@start", start),
                new SqlParameter("@stop", stop)});
            adapter.Fill(entries);
        }
    }
    return entries;
}


Update

I'd like to summarize and provide some additional information I've learned from the discussion here and debugging efforts since I originally posted this question.

I am refactoring old code that retrieved records from a database, collected those records as an array, and then later iterated through the array to populate a DataGridView row by row. Threading was originally implemented to compensate and keep the UI responsive during the unnecessary looping. I have since stripped out Thread/Invoke; everything now occurs on the same execution thread (thank you, Sam).

I am attempting to replace the slow, unwieldy approach using a DataTable which I can fill with a DataAdapter, and assign to the DataGridView through it's DataSource property (above code updated).

I've iterated through the entries DataTable's rows to verify the table contains the expected data before assigning it as the DataGridView's DataSource.

foreach (DataRow row in entries.Rows)
{
    System.Diagnostics.Trace.WriteLine(
        String.Format("{0} {1} {2}", row[0], row[1], row[2]));
}

One of the column of the DataGridView is a custom DataGridViewColumn to stylize the event_type value. I apologize I didn't mention this before in the original post but I wasn't aware it was important to my problem. I have converted this column temporarily to a standard DataGridViewTextBoxColumn control and am no longer experiencing the Exception.

The fields in the DataTable are appended to the list of fields that have been pre-specified in Design view of the DataGridView. The records' values are being populated in these appended fields. When the run time attempts to render the cell a null value is provided (as the value that should be rendered is done so a couple columns over).

In light of this, I am re-titling and re-tagging the question. I would still appreciate it if others who have experienced this can instruct me on how to go about binding the DataTable to the existing column definitions of the DataGridView.

解决方案

You need to ensure each column's DataPropertyName property is set to the corresponding name of the DataColumn's ColumnName.

You may also need to set the DataGridView's AutoGenerateColumns property to false.

I found the solution here.

这篇关于C#将DataTable绑定到现有的DataGridView列定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆