Source code: 13033480 group sharing
Procedure]
1. Right-click Web → add new project Web configuration file
2. Add a connection string
[Html]
<ConnectionStrings>
<Add name = "SQLConnString1" connectionString = "server =. \ SQLEXPRESS; database = NetShop; integrated security = SSPI; min pool size = 4; max pool size = 4; "providerName =" System. data. sqlClient "/>
</ConnectionStrings>
3. Copy CategoryInfo. c in the Model.
4. Add the ListBox control to Default. aspx.
[Html]
<Div>
<Asp: ListBox ID = "lstCategories" runat = "server">
</Asp: ListBox>
</Div>
5. Add the following code to Default. aspx. cx:
[Csharp]
Public partial class _ Default: System. Web. UI. Page
{
Private const string SQL _SELECT_CATEGORIES = "SELECT CategoryId, Name, Descn FROM Category ";
Protected void Page_Load (object sender, EventArgs e)
{
IList <CategoryInfo> categories = new List <CategoryInfo> ();
// Basic database operations
String connectionString = ConfigurationManager. ConnectionStrings ["SQLConnString1"]. ConnectionString;
SqlCommand cmd = new SqlCommand ();
SqlConnection conn = new SqlConnection (connectionString );
Conn. Open ();
Cmd. Connection = conn;
Cmd. CommandText = SQL _SELECT_CATEGORIES;
Cmd. CommandType = CommandType. Text;
SqlDataReader rdr = cmd. ExecuteReader (CommandBehavior. CloseConnection );
// Save the data to the Model.
While (rdr. Read ())
{
CategoryInfo cat = new CategoryInfo (rdr. GetString (0), rdr. GetString (1), rdr. GetString (2 ));
Categories. Add (cat );
}
Conn. Close ();
// Bind data to the user interface
LstCategories. DataSource = categories;
LstCategories. DataTextField = "Name ";
LstCategories. DataValueField = "ID"; // is it better if the fields in the Model are the same as those in the database table?
LstCategories. DataBind ();
}
}
6. Classes in List, ConfigurationManager, and Model are used in the code. You need to add references and import the corresponding namespaces.
Using System. Collections. Generic;
Using System. Configuration;
Using NetShop. Model;
7. Browse and view results
[Technical points]
1. connection string
2. Data Class Library Model
3. IList and List
From ASP. NET Technology