Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
755 views
in Technique[技术] by (71.8m points)

winforms - How do I dynamically create a DataGridView in C#?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

<body>
    <form id="form" runat="server" />
    <asp:PlaceHolder id="ph" runat="server" />
</body>

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...