现在的位置: 首页 > 综合 > 正文

自己手动创建dataset的方法(不用从数据库倒入)

2013年04月18日 ⁄ 综合 ⁄ 共 1120字 ⁄ 字号 评论关闭

有时候会遇到将数据库查询出来的字符串进行分割,整理,再付给某个控键。这样就需要把整理好的字符串放在一个dataset中,这个dataset只好手动自己创建,并且将字符串添进去。一下这个例子非常的好。

下面的示例创建一个 DataTable、添加两个用于确定表的架构的 datacolumn 对象、使用newrow()方法创建几个新的 DataRow 对象。然后使用 add 方法将这些 DataRow 对象添加到 DataRowCollection 中。

private void MakeDataTableAndDisplay()
{
    // Create new DataTable and DataSource objects.
    DataTable table = new DataTable();

    // Declare DataColumn and DataRow variables.
    DataColumn column;
    DataRow row;
    DataView view;

    // Create new DataColumn, set DataType, ColumnName and add to DataTable.   
    column = new DataColumn();
    column.DataType = System.Type.GetType("System.Int32");
    column.ColumnName = "id";
    table.Columns.Add(column);

    // Create second column.
    column = new DataColumn();
    column.DataType = Type.GetType("System.String");
    column.ColumnName = "item";
    table.Columns.Add(column);

    // Create new DataRow objects and add to DataTable.   
    for(int i = 0; i < 10; i++)
    {
        row = table.newrow();
        row["id"] = i;
        row["item"] = "item " + i.ToString();
        table.Rows.Add(row);
    }

    // Create a DataView using the DataTable.
    view = new DataView(table);

    // Set a DataGrid control's DataSource to the DataView.
    dataGrid1.DataSource = view;
}
 

抱歉!评论已关闭.