导航
  • 主页
  • .NET Framework
  • ASP
  • Web Services
  • .NET互联网桌面应用
  • VB
  • 图表区
  • 分析与设计
  • 组件/控件开发
  • AppLauncher
  • 问答

在datagrid的某一列绑定droplist,怎么做

jourmen IBM 架构师  2004-04-06 11:54:10
我用datagrid更新某一行时,其中一列的需要用下拉选择,用到droplist

怎样做呢??

大家帮帮我

谢谢!

有代码例子可以参考一下么?
...全文
31 点赞 收藏 7
写回复
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
helloqiqi 2004-04-06
加入一个模板列,再把droplist加进去
回复
jourmen 2004-04-06
太谢谢了


我先看看;)

回复
hychieftain 2004-04-06
建议一本书
《构建Web解决方案---应用ASP.NET和ADO.NET》 专门说Datagrid的,只是翻译的太不好了,上面就是本书的例子
回复
ppp80 2004-04-06
加模版列,然后把droplist放到模版列里,它的数据邦定可以在IDataGrid_temCreated中实现!
回复
hychieftain 2004-04-06
不好意思,上面的是脚注带DropList,下面才是DropList列
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>

<html>
<title>Adapting to Data - Arrays</title>
<style>
hr {height:2px;color:black;}
.StdText {font-family:verdana;font-size:9pt;font-weight:bold;}
.StdTextBox {font-family:verdana;font-size:9pt;border:solid 1px black;filter:progid:DXImageTransform.Microsoft.dropshadow(OffX=2, OffY=2, Color='gray', Positive='true');}
.Shadow {filter:progid:DXImageTransform.Microsoft.dropshadow(OffX=2, OffY=2, Color='gray', Positive='true');}
</style>


<script runat="server">
public void Page_Load(Object sender, EventArgs e)
{
// Initialize only the first time...
if (!Page.IsPostBack)
{
lblURL.Text = Request.Url + "<hr>";
}
}

public void OnLoadData(Object sender, EventArgs e)
{
// Prepare the command strings
String strCmd1 = "SELECT employeeid, lastname, firstname, titleofcourtesy, title, ISNULL(reportsto,0) As boss FROM Employees";

StringBuilder sb = new StringBuilder("");
sb.Append("SELECT et.employeeid, t.territorydescription FROM EmployeeTerritories AS et ");
sb.Append("INNER JOIN Territories AS t ");
sb.Append("ON t.territoryid = et.territoryid");
String strCmd2 = sb.ToString();

// Executes the commands
DataSet ds = new DataSet();
SqlDataAdapter da;
SqlConnection conn = new SqlConnection(txtConn.Text);

da = new SqlDataAdapter(strCmd1, conn);
da.Fill(ds, "EmployeesTable");

da = new SqlDataAdapter(strCmd2, conn);
da.Fill(ds, "TerritoriesTable");

// Create a relation between the two tables
DataColumn dc1 = ds.Tables["EmployeesTable"].Columns["employeeid"];
DataColumn dc2 = ds.Tables["TerritoriesTable"].Columns["employeeid"];
DataRelation drel = new DataRelation("EmployeesAndTerritories", dc1, dc2);
ds.Relations.Add(drel);


// Bind the data
grid.DataSource = ds.Tables["EmployeesTable"];

// Display the data
grid.DataBind();
}

ArrayList GetTerritories(DataRowView drv)
{
// Extract the underlying row from the DataRowView object
DataRow dr = drv.Row;

// Retrieve the child rows according to the data relation
DataRow[] adr = dr.GetChildRows("EmployeesAndTerritories");

// Create and return an array made of the values in the
// TerritoryDescription column
ArrayList a = new ArrayList();
foreach(DataRow tmp in adr)
a.Add(tmp["territorydescription"]);
return a;
}


String GetProperGifFile(int bossID)
{
if (bossID != 0)
return "checked.gif";
return "unchecked.gif";
}

</script>


<body bgcolor="ivory" style="font-family:arial;font-size:9pt">

<!-- ASP.NET topbar -->
<h2>Adapting to Data - Arrays</h2>
<asp:Label runat="server" cssclass="StdText" font-bold="true">Current path: </asp:label>
<asp:Label runat="server" id="lblURL" cssclass="StdText" style="color:blue"></asp:label>

<form runat="server">

<table>
<tr>
<td><asp:label runat="server" text="Connection String" cssclass="StdText" /></td>
<td><asp:textbox runat="server" id="txtConn"
Enabled="false"
cssclass="StdTextBox"
width="700px"
text="DATABASE=Northwind;SERVER=localhost;UID=sa;PWD=;" /></td></tr>
</table>

<br><br>
<asp:linkbutton runat="server" id="btnLoad" text="Go get data..." onclick="OnLoadData" />

<hr>

<asp:DataGrid id="grid" runat="server"
AutoGenerateColumns="false"
CssClass="Shadow" BackColor="white"
CellPadding="2" CellSpacing="0"
BorderStyle="solid" BorderColor="black" BorderWidth="1"
font-size="x-small" font-names="verdana">

<AlternatingItemStyle BackColor="palegoldenrod" />
<ItemStyle BackColor="beige" />
<HeaderStyle ForeColor="white" BackColor="brown" Font-Bold="true" HorizontalAlign="center" />

<columns>
<asp:BoundColumn runat="server" HeaderText="ID" DataField="employeeid">
<itemstyle backcolor="lightblue" font-bold="true" />
</asp:BoundColumn>

<asp:TemplateColumn runat="server" HeaderText="Employee Name">
<itemtemplate>
<asp:label runat="server"
style="margin-left:5;margin-right:5"
Text='<%# DataBinder.Eval(Container.DataItem, "TitleOfCourtesy") + "<b> " +
DataBinder.Eval(Container.DataItem, "LastName") + "</b>" + ", " +
DataBinder.Eval(Container.DataItem, "FirstName") %>' />
</itemtemplate>
</asp:TemplateColumn>

<asp:BoundColumn runat="server" DataField="title" HeaderText="Position" />

<asp:TemplateColumn HeaderText="Reports" itemstyle-horizontalalign="Center">
<itemtemplate>
<asp:image runat="server"
imageurl='<%# GetProperGifFile((int)DataBinder.Eval(Container.DataItem, "boss")) %>' />
</itemtemplate>
</asp:TemplateColumn>


<asp:TemplateColumn HeaderText="Territories">
<itemtemplate>
<asp:dropdownlist runat="server"
backcolor="ivory"
width="120px"
datasource='<%# GetTerritories((DataRowView) Container.DataItem) %>'
/>
</itemtemplate>
</asp:TemplateColumn>

</columns>
</asp:DataGrid>

</form>

</body>
</html>
回复
beibeilong 2004-04-06
用<ItemTemplate>来创建下拉列表
或者换个方式,用htmltable不用datagrid
回复
hychieftain 2004-04-06
完整的示例,copy到你的项目即可,要有SQL Server
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>


<html>
<title>Multiple Column Views</title>
<style>
hr {height:2px;color:black;}
.StdText {font-family:verdana;font-size:9pt;font-weight:bold;}
.StdTextBox {font-family:verdana;font-size:9pt;border:solid 1px black;filter:progid:DXImageTransform.Microsoft.dropshadow(OffX=2, OffY=2, Color='gray', Positive='true');}
.Shadow {filter:progid:DXImageTransform.Microsoft.dropshadow(OffX=2, OffY=2, Color='gray', Positive='true');}
</style>


<script runat="server">
public void Page_Load(Object sender, EventArgs e)
{
// Initialize only the first time...
if (!Page.IsPostBack)
{
lblURL.Text = Request.Url + "<hr>";
grid.Attributes["CurrentViewFile"] = "courtesylastfirst.ascx";
}


}

public void UpdateView()
{
SqlConnection conn = new SqlConnection(txtConn.Text);
SqlDataAdapter da = new SqlDataAdapter(txtCommand.Text, conn);

DataSet ds = new DataSet();
da.Fill(ds, "MyTable");

DataView dv = ds.Tables["MyTable"].DefaultView;
grid.DataSource = dv;
dv.Sort = grid.Attributes["SortExpression"];

TemplateColumn tc = (TemplateColumn) grid.Columns[1];
tc.ItemTemplate = Page.LoadTemplate(grid.Attributes["CurrentViewFile"]);

grid.DataBind();
}

public void OnLoadData(Object sender, EventArgs e)
{
UpdateView();
}

public void ItemCommand(Object sender, DataGridCommandEventArgs e)
{
if (e.CommandName == "applyview")
{
DropDownList ddViews = (DropDownList) e.Item.FindControl("ddViews");
String strFile = ddViews.SelectedItem.Value;

grid.Attributes["CurrentViewFile"] = strFile;
grid.Attributes["ViewIndex"] = ddViews.SelectedIndex.ToString();

UpdateView();

}
}

public void SortCommand(Object sender, DataGridSortCommandEventArgs e)
{
if (e.SortExpression != "*")
grid.Attributes["SortExpression"] = e.SortExpression;
else
{
// Retrieves the drop-down list control through its ID
DataGridItem dgi = (DataGridItem) e.CommandSource;
DropDownList dd = (DropDownList) dgi.FindControl("ddSort");

// Retrieves the sorting expression from the list
grid.Attributes["SortExpression"] = dd.SelectedItem.Value;

// Persists the currently selected drop-down item
grid.Attributes["FieldIndex"] = dd.SelectedIndex.ToString();
}

UpdateView();
}

public void ItemCreated(Object sender, DataGridItemEventArgs e)
{
ListItemType lit = e.Item.ItemType;
if (lit == ListItemType.Header)
{
// Create and fill a drop-down list control
DropDownList dd = new DropDownList();
dd.ID = "ddSort";
ListItem li1, li2, li3;

// ListItem constructor takes Text and Value for the item
li1 = new ListItem("Title of courtesy", "titleofcourtesy");
dd.Items.Add(li1);

li2 = new ListItem("Last Name", "lastname");
dd.Items.Add(li2);

li3 = new ListItem("First Name", "firstname");
dd.Items.Add(li3);

// Selects the item, if any, that was selected last time
dd.SelectedIndex = Convert.ToInt32(grid.Attributes["FieldIndex"]);

// Add the drop-down list to the header of the 2nd column
TableCell cell = (TableCell) e.Item.Controls[1];
cell.Controls.Add(dd);
}

if (lit == ListItemType.Footer)
{
e.Item.Cells.RemoveAt(2);
e.Item.Cells.RemoveAt(0);
e.Item.Cells[0].ColumnSpan = 3;

// Populate the Views list
DropDownList ddViews = (DropDownList) e.Item.FindControl("ddViews");
ListItem l;
l = new ListItem("Ms. Surname, Name", "courtesylastfirst.ascx");
ddViews.Items.Add(l);
l = new ListItem("Name Surname - (Ms.)", "firstlastcourtesy.ascx");
ddViews.Items.Add(l);

ddViews.SelectedIndex = Convert.ToInt32(grid.Attributes["ViewIndex"]);
}
}


</script>


<body bgcolor="ivory" style="font-family:arial;font-size:9pt">

<!-- ASP.NET topbar -->
<h2>Multiple Views for a Template Column</h2>
<asp:Label runat="server" cssclass="StdText" font-bold="true">Current path: </asp:label>
<asp:Label runat="server" id="lblURL" cssclass="StdText" style="color:blue"></asp:label>

<form runat="server">

<table>
<tr>
<td><asp:label runat="server" text="Connection String" cssclass="StdText" /></td>
<td><asp:textbox runat="server" id="txtConn"
Enabled="false"
cssclass="StdTextBox"
width="600px"
text="DATABASE=Northwind;SERVER=localhost;UID=sa;PWD=;" /></td></tr>

<tr>
<td><asp:label runat="server" text="Command Text" cssclass="StdText"/></td>
<td><asp:textbox runat="server" id="txtCommand"
Enabled="false"
width="600px"
cssclass="StdTextBox"
text="SELECT employeeid, titleofcourtesy, firstname, lastname, title, country FROM Employees" /></td></tr></table>

<br><br>
<asp:linkbutton runat="server" id="btnLoad" text="Go get data..." onclick="OnLoadData" />

<hr>
<asp:label runat="server" id="lblOutput" />

<asp:DataGrid id="grid" runat="server"
AutoGenerateColumns="false"
AllowSorting="true"
ShowFooter="true"
OnSortCommand="SortCommand"
OnItemCommand="ItemCommand"
OnItemCreated="ItemCreated"
CssClass="Shadow" BackColor="white"
CellPadding="2" CellSpacing="2" GridLines="none"
BorderStyle="solid" BorderColor="black" BorderWidth="1"
font-size="x-small" font-names="verdana">

<AlternatingItemStyle BackColor="palegoldenrod" />
<ItemStyle BackColor="beige" />
<HeaderStyle ForeColor="white" BackColor="brown" Font-Bold="true" />

<columns>
<asp:BoundColumn runat="server" DataField="employeeid" HeaderText="ID" SortExpression="employeeid">
<itemstyle backcolor="lightblue" font-bold="true" />
</asp:BoundColumn>


<asp:TemplateColumn runat="server" HeaderText="Sort by " SortExpression="*">
<itemtemplate>
<asp:label runat="server"
Text='<%# DataBinder.Eval(Container.DataItem, "TitleOfCourtesy") + "<b> " +
DataBinder.Eval(Container.DataItem, "LastName") + "</b>" + ", " +
DataBinder.Eval(Container.DataItem, "FirstName") %>' />
</itemtemplate>
<footertemplate>
<b>View:</b>
<asp:dropdownlist runat="server" id="ddViews" />
<asp:linkbutton runat="server" id="lnkApply" Text="Apply" commandname="applyview" />
</footertemplate>
</asp:TemplateColumn>


<asp:BoundColumn runat="server" DataField="title" HeaderText="Position" />
<asp:BoundColumn runat="server" DataField="country" HeaderText="From" />
</columns>
</asp:DataGrid>

</form>

</body>
</html>
回复
发动态
发帖子
.NET技术社区
创建于2007-09-28

5.8w+

社区成员

.NET技术交流专区
申请成为版主
社区公告
暂无公告