GridView不显示我的数据源

时间:2013-12-02 10:08:53

标签: c# winforms gridview

我有gridview“gvData”,我需要将我的函数数据提取到gridview: (我正在使用c#应用程序)

  algorithm.prison obj=new prison();
     gvData.DataSource=  obj.TitForTat();

运行后我有一个空的gridview。 这是我的代码:

 public DataSet TitForTat()
    {
        DataSet ds = new DataSet();
        DataTable dt = new DataTable("myt");
        dt.Columns.Add(new DataColumn("iteration", typeof(int)));
        dt.Columns.Add(new DataColumn("prison1", typeof(string)));
        dt.Columns.Add(new DataColumn("prison2", typeof (string)));
        prison[] prisons = new prison[2];
        prisons[0] = new prison();
        prisons[1] = new prison();
        //---------------------------
        DataRow dr = dt.NewRow();
        prisons[0]._state = "c";
        prisons[1]._state = valueOfState[rd.Next(0, 1)];
        dr["iteration"] = 0;
        dr["prison1"] = "c";
        dr["prison2"] = prisons[1]._state;
        dt.Rows.Add(dr);
        //----------------------
        for (int i = 1; i <= _iteration; i++)
        {
            prisons[0]._state = prisons[1]._state;
            prisons[1]._state = valueOfState[rd.Next(0, 1)];
            DataRow dr1 = dt.NewRow();
            dr1["iteration"] =i;

            dr1["prison1"] = prisons[0]._state;
            dr1["prison2"] = prisons[1]._state;
            dt.Rows.Add(dr1);
        }

        ds.Tables.Add(dt);
        return ds;
    }

1 个答案:

答案 0 :(得分:1)

如果是ASP.NET - webforms GridView - 控件,您需要在分配DataSource后致电DataBind()

gvData.DataSource = obj.TitForTat();
gvData.DataBind();

如果是winforms,则必须设置DataMember属性,如果您使用的是DataSet而不是DataTable

gvData.DataSource = obj.TitForTat();
gvData.DataMember = "myt";  

...或首先使用DataTable

DataSet ds = obj.TitForTat();
if(ds.Tables.Count > 0)
    gvData.DataSource = ds.Tables[0];