日期:2012-08-31  浏览次数:21247 次

有的时候我们需要
(1)在编辑的时候用下拉框选择,并且默认为数据库的内容
(2)使用下拉框过滤数据
(3)使用css统一定制DataGrid
下面给出代码:
数据结构:
表dep:depid(标识主键),depname(学院名字)
表stu:stuid(标识主键),stuname(学生名字),studepid(学院id=表dep.depid)

前台:
<%@ Page language="c#" Codebehind="WebForm28.aspx.cs" AutoEventWireup="false" Inherits="csdn.WebForm28" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
<title>WebForm28</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name="vs_defaultClientScript" content="JavaScript">
<link href="css.css" rel="stylesheet" type="text/css">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body>
<form id="Form1" method="post" runat="server">
<asp:DropDownList id="DropDownList1" runat="server" AutoPostBack="True"></asp:DropDownList>
<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False" CellSpacing="1" BorderWidth="0px"
CellPadding="5" CssClass="border" OnEditCommand="edit" OnCancelCommand="cancel" OnUpdateCommand="update"
DataKeyField="stuid">
<ItemStyle CssClass="item"></ItemStyle>
<HeaderStyle CssClass="header"></HeaderStyle>
<Columns>
<asp:TemplateColumn HeaderText="姓名">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem,"stuname") %>
</ItemTemplate>
<EditItemTemplate>
<asp:TextBox id="name" Runat="server" Text='<%# DataBinder.Eval(Container.DataItem,"stuname") %>' Width="88px">
</asp:TextBox>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:TemplateColumn HeaderText="学院">
<ItemTemplate>
<%# DataBinder.Eval(Container.DataItem,"depname") %>
</ItemTemplate>
<EditItemTemplate>
<asp:DropDownList ID="dep" Runat="server"></asp:DropDownList>
</EditItemTemplate>
</asp:TemplateColumn>
<asp:EditCommandColumn ButtonType="PushButton" UpdateText="更新" CancelText="取消" EditText="编辑"></asp:EditCommandColumn>
</Columns>
</asp:DataGrid>
</form>
</body>
</HTML>
后台:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace csdn
{
/// <summary>
/// WebForm28 的摘要说明。
/// </summary>
public class WebForm28 : System.Web.UI.Page
{
protected System.Web.UI.WebControls.DropDownList DropDownList1;
protected System.Web.UI.WebControls.DataGrid DataGrid1;

private void Page_Load(object sender, System.EventArgs e)
{
// 在此处放置用户代码以初始化页面
if(!IsPostBack)
{
SetBind();
SetBind2();
}
}

protected void SetBind()
{

SqlConnection conn=new SqlConnection(System.Configuration.Configur