To GridView Control θα πρέπει να έχει ώς DataSource κάποιον πίνακα με δεδομένα (DataTable), και καθένα από τα DropDownLists να δίνει την τιμή για μία στήλη από αυτόν τον πίνακα. (Άν κατάλαβα καλά το σενάριο)
Έχουμε λοιπόν έναν υποθετικό πίνακα με δύο στήλες, Product και ProductEvaluation.
H aspx Σελίδα μας θα είναι κάπως έτσι:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<A href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd</A>">
<html xmlns="<A href="http://www.w3.org/1999/xhtml">http://www.w3.org/1999/xhtml</A>" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="True">
</asp:GridView>
<asp:Button ID="clearButton" runat="server" Text="Clear Grid" OnClick="clearButton_Click" /> <br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>PC</asp:ListItem>
<asp:ListItem>Motherboard</asp:ListItem>
<asp:ListItem>Hard Disk</asp:ListItem>
<br />
<asp:DropDownList ID="DropDownList2" runat="server" Width="98px">
<asp:ListItem>Good</asp:ListItem>
<asp:ListItem>Not Bad</asp:ListItem>
<asp:ListItem>Bad</asp:ListItem>
</asp:DropDownList>
</div ID="addButton" runat="server" OnClick="addButton_Click" Text="Add" Width="76px">
</form>
</body>
</html>
Παρατήρησε πως το GridView Control έχει το Property AutoGenerateColumns="True"
Λοιπόν, πάμε στο cs File όπου θα κάνουμε την ουσιαστική δουλειά.Εκεί έχουμε
//Declare the DataTable
private static DataTable dt;
protected void Page_Load(object sender, EventArgs e)
{
//Create the DataTables Columns
//The First Time the Page is Load
if (!IsPostBack)
{
dt = new DataTable();
dt.Columns.Add("Product");
dt.Columns.Add("Value");
}
//Bind the GridView Control to the DataTable
GridView1.DataSource = dt;
}
protected void addButton_Click(object sender, EventArgs e)
{
//Create a new Row from the DataTable
DataRow dr = dt.NewRow();
//Get The Row Values from the DropDownLists Texts
object[] obj = { DropDownList1.Text, DropDownList2.Text };
//Fill the new DataRow with those Values
dr.ItemArray = obj;
//Add the new DataRow to the DataTable
dt.Rows.Add(dr);
//Refresh The GridView Data by ReBinding it
//to the Changed DataTable
GridView1.DataBind();
}
protected void clearButton_Click(object sender, EventArgs e)
{
//Clear All the DataRows from
//the DataTable
dt.Clear();
//Refresh The GridView Data by ReBinding it
//to the Changed DataTable
GridView1.DataBind();
}
Όπως βλέπεις, ορίζουμε αρχικά τον πίνακα, τον "δένουμε" στο GridView και έπειτα αντιδρούμε στον πίνακα (και κατά επέκταση στο GridView) ανάλογα με το κουμπί που πάτησε ο χρήστης.
Άν σε κάποιο σημείο χρειάζεσαι παραπάνω επεξήγηση, εδώ είμαστε.