How do I dynamically create a DataGridView in C#?

前端 未结 3 1213
深忆病人
深忆病人 2020-12-20 05:15

How do I dynamically create a DataGridView in C#? Could you please provide an example?

3条回答
  •  不思量自难忘°
    2020-12-20 05:41

    You can create it like any other controls.

    place a PLACEHOLDER control in your page (this will serve as start point)

    so your page looks like

    
        

    Then, in your code behind, just create and add controls to the Place Holder

    // Let's create our Object That contains the data to show in our Grid first
    string[] myData = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I" };
    
    // Create the Object
    GridView gv = new GridView();
    
    // Assign some properties
    gv.ID = "myGridID";
    gv.AutoGenerateColumns = true;
    
    // Assing Data (this can be a DataTable or you can create each column through Columns Colecction)
    gv.DataSource = myData;
    gv.DataBind();
    
    // Now that we have our Grid all set up, let's add it to our Place Holder Control
    ph.Controls.Add(gv);
    

    Maybe you want to add more controls?

    // How about adding a Label as well?
    Label lbl = new Label;
    lbl.ID = "MyLabelID";
    lbl.Text = String.Format("Grid contains {0} row(s).", myData.Length);
    
    ph.Controls.Add(lbl);
    
    // Done!
    

    Hope it helps get you started

提交回复
热议问题