【问题标题】:Bind single datagrid with two diff datasources (Stored Procedure output and ArrayList)将单个数据网格与两个不同的数据源(存储过程输出和 ArrayList)绑定
【发布时间】:2015-08-11 22:54:57
【问题描述】:

我有一个数据网格,我想用它显示三列。 我已经使用存储过程将一些记录显示到数据网格中。

存储过程是:

procedure [dbo].[allKeys]
AS 
select id,key,username from keys_TB

此过程中的密钥是加密的,所以需要转换它我已经完成了转换并保留了这些密钥是 ArrayList。

但问题是已经将剩余的 id,username 列绑定到 datagrid,无法将 ArrayList 绑定到 datagrid。

后面的代码:

DataSet ds = clsBusinessLogic.allKeys();
dgrv_allkey.DataSource = ds.Tables[0];
dgrv_allkey.AutoGenerateColumns = false;
dgrv_allkey.Columns["id"].DataPropertyName = "id";
DataGridViewColumn id = dgrv_allkey.Columns[0];
this.dgrv_allkey.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
id.Width = 60;

dgrv_allkey.Columns["username"].DataPropertyName = "username";
DataGridViewColumn Custname = dgrv_allkey.Columns[2];
Custname.Width = 199;
this.dgrv_allkey.Columns[2].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;

这就是我将 id 和用户名绑定到数据网格但对密钥没有任何线索的方式。

我已经通过 clsBusinessLogic.allKeys() 方法调用了存储过程 [allKeys]

【问题讨论】:

  • 永远不要使用ArrayList。它已经过时了十多年。
  • @JohnSaunders 请提出另一种解决方案...

标签: c# datagridview


【解决方案1】:

首先在网格中添加一个数据绑定完成事件:

dgrv_allkey.DataBindingComplete += dgrv_allkey_DataBindingComplete;

然后将存储过程的结果集添加为网格数据源:

dgrv_allkey.DataSource = ds.Tables[0];
dgrv_allkey.Columns["id"].DataPropertyName = "id";
////and other formating what ever needed. 

由于设置了数据源,该事件将被触发,然后在此事件中更改每一行的关键单元格的值。

private void dgrv_allkey_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    // Change Column Value for the DataGridView. 
    foreach (DataGridViewColumn i in dataGridView1.Columns)
    {
        if (i.Name == "key")
        {
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                string oldvalue = row.Cells["key"].Value as string;

                if (!string.IsNullOrEmpty(oldvalue))
                {
                    // perform decoding here and set the decoded value here..
                }
            }
        }
    }
}

【讨论】:

  • 我无法从该数据网格中获取要转换的字符串...实际上是“oldvalue = row.Cells["key"].Value as string;"返回空.../。现在不知道为什么
  • 你能查一下手表,数据表列名是什么?
  • 一切都是正确的..但是当尝试从 datagrid 代码中获取值时返回 null
  • gridview1.rows 显示确切的值,现在它显示 5 行.. 和 row.Cells 给出特定行的索引..
猜你喜欢
  • 1970-01-01
  • 2011-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-04
相关资源
最近更新 更多