我想在GirdView控件的编辑功能中,把由TextBox输入换成DropDownlist从数据库取出的值。实现如下,GridView控件绑定AccessDataSourc1,选取Class表中的所有列。DropDownlist控件绑定AccessDataSourc2,选取Product表中的ProName列(注:已将要由Dropdownlist选取的列转化为模板列),可是在Dropdownlist的SelectedValue中只能选取AccessDataSourc1中Class表的列,明明Dropdownlist绑定的是AccessDataSourc2 Product表中的ProName列。
DataSourceID="AccessDataSource1" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowUpdating="GridView1_RowUpdating">
<Columns>
<asp:TemplateField HeaderText="采购物品" SortExpression="Content">
<EditItemTemplate>
<asp:DropDownList ID="DropDownList1" runat="server"
DataTextField="PurchaseName" DataValueField="PurchaseName" DataSourceID="AccessDataSource2"
>
</asp:DropDownList>
<asp:AccessDataSource ID="AccessDataSource2" runat="server" DataFile="~/App_Data/#Date.mdb"
SelectCommand="SELECT [PurchaseName] FROM [Item]" ></asp:AccessDataSource> </EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label2" runat="server" Text='<%# Bind("Content") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="160px" />
</asp:TemplateField>
<asp:BoundField DataField="Type" HeaderText="型号" SortExpression="Type">
<ItemStyle Width="160px" />
</asp:BoundField>
<asp:BoundField DataField="Notice" HeaderText="备注" SortExpression="Notice">
<ItemStyle Width="160px" />
</asp:BoundField>
<asp:BoundField DataField="RefPrice" HeaderText="参考价格" SortExpression="RefPrice">
<ItemStyle Width="160px" />
</asp:BoundField>
<asp:TemplateField HeaderText="数量" SortExpression="Number">
<EditItemTemplate>
<asp:TextBox ID="NumberReq" runat="server" Text='<%# Bind("Number") %>' Columns="10"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server" ControlToValidate="NumberReq"
ErrorMessage="*" MaximumValue="9999" MinimumValue="1"></asp:RangeValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="*" ControlToValidate="NumberReq"
></asp:RequiredFieldValidator> </EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Number") %>'></asp:Label>
</ItemTemplate>
<ItemStyle Width="160px" />
</asp:TemplateField>
<asp:TemplateField HeaderText="操作" ShowHeader="False">
<EditItemTemplate>
<asp:Button ID="Button11" runat="server" CausesValidation="True" CommandName="Update"
Text="更新" /> <asp:Button ID="Button2" runat="server" CausesValidation="False"
CommandName="Cancel" Text="取消" />
</EditItemTemplate>
<ItemTemplate>
<asp:Button ID="Button2" runat="server" CausesValidation="False" CommandName="Edit"
Text="编辑" /> <asp:Button ID="Button3" runat="server" CausesValidation="False"
CommandName="Delete" Text="删除" OnClientClick="return confirm('确认要删除吗?')"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:Button ID="Button1" runat="server" CausesValidation="false" CommandName="Insert"
Text="新建" OnClick="Button1_Click1"/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<EmptyDataTemplate> </EmptyDataTemplate>
<FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<RowStyle BackColor="#F7F6F3" ForeColor="#333333" HorizontalAlign="Center" VerticalAlign="Middle" />
<PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
<SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
<HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
<EditRowStyle BackColor="#999999" />
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
</asp:GridView>
<asp:AccessDataSource ID="AccessDataSource1" runat="server" DataFile="~/App_Data/#Date.mdb"
DeleteCommand="DELETE FROM [PurchaseContent] WHERE [ID] = ?" InsertCommand="INSERT INTO [PurchaseContent] ([Content], [Type], [Notice], [RefPrice], [Number]) VALUES (?, ?, ?, ?, ?)"
SelectCommand="SELECT * FROM [PurchaseContent]" UpdateCommand="UPDATE [PurchaseContent] SET [Content] = ?, [Type] = ?, [Notice] = ?, [RefPrice] = ?, [Number] = ? WHERE [ID] = ?">
<DeleteParameters>
<asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="Content" Type="String" />
<asp:Parameter Name="Type" Type="String" />
<asp:Parameter Name="Notice" Type="String" />
<asp:Parameter Name="RefPrice" Type="String" />
<asp:Parameter Name="Number" Type="Int32" />
<asp:Parameter Name="ID" Type="Int32" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="Content" Type="String" />
<asp:Parameter Name="Type" Type="String" />
<asp:Parameter Name="Notice" Type="String" />
<asp:Parameter Name="RefPrice" Type="String" />
<asp:Parameter Name="Number" Type="Int32" />
</InsertParameters>
</asp:AccessDataSource>Dropdownlist 的SelectedValue中只能选取AccessDataSourc1的列
==
<asp:DropDownList ID="DropDownList1" runat="server" DataTextField="PurchaseName" DataValueField="PurchaseID" DataSourceID="AccessDataSource2" SelectedValue='<%# Eval("PurchaseID")%>'></asp:DropDownList>
第一:你可以一个一个用foreach遍历上去。
第二:写个存储过程。将结果集一次加进去。请楼下补充
1)是否在前台DropDownlist代码中加入SelectedValue=<%# bind("PurchaseName")就可以自动更新数据(这样做会有错误提示,说PurchaseName不是SelectedValue的属性,也就是我本贴问的问题),后台不用添加任何代码呢?
2)如果需要在后台添加OnRowUpdating事件代码,请给下,谢谢。
==
对的,前提是你使用SqlDataSource控件SelectedValue= '<%# Bind("PurchaseName") %>'
2、你可以把AccessDataSourc2的SelectCommand改成:"SELECT [ID], [PurchaseName] FROM [Item]"
3、改DropDownList的DataValueField
<asp:DropDownList ID="DropDownList1" runat="server"
DataTextField="PurchaseName" DataValueField="ID" DataSourceID="AccessDataSource2"
>这样PurchaseContent的Content字段会存对应的ID,将来如果想用GridView之类的控件显示时,你可以把DataSource控件的SelectCommand写成:
SELECT PurchaseContent.ID, Type, Notice, RefPrice, Number, Release, (select Content from Item where Item.ID=PurchaseContent.Content) as Content from PurchaseContent
<asp:DropDownList ID="DropDownList1" runat="server"
DataTextField="PurchaseName" DataValueField="ID" DataSourceID="AccessDataSource2" SelectedValue='<%# Bind("Content") %>'
>
可以参照下事例
自己学习下..地址:
http://blog.csdn.net/insus/archive/2008/03/26/2221260.aspx
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
DropDownList ddl = GridView1.Rows[e.RowIndex].FindControl("DropDownlist1") as DropDownList;
if (ddl != null)
{
string Name = ddl.SelectedValue;
OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + HttpContext.Current.Server.MapPath("~/App_Data/#date.mdb"));
conn.Open();
OleDbCommand cmd = new OleDbCommand("UPDATE PurchaseContent SET Content='" + Name + "' WHERE ID = @ID", conn);
OleDbParameter parm1 = new OleDbParameter("@ID", SqlDbType.Int);
parm1.Value =GridView1.DataKeys //这行不会写了,怎么才能获得ID????
cmd.Parameters.Add(parm1);
cmd.ExecuteNonQuery();
conn.Close();
}
}
{
DropDownList ddl = GridView1.Rows[e.RowIndex].FindControl("DropDownlist1") as DropDownList;
if (ddl != null)
{
string Name = ddl.SelectedValue;
OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" + HttpContext.Current.Server.MapPath("~/App_Data/#date.mdb"));
if (conn.State == ConnectionState.Closed)
{
conn.Open();
}
int ID = (int)GridView1.DataKeys[e.RowIndex].Value;
string sql = "UPDATE PurchaseContent SET Content =" +Name+" WHERE ID = " + ID;
OleDbCommand cmd = new OleDbCommand(sql, conn);
cmd.ExecuteNonQuery();
conn.Close();
GridView1.EditIndex = -1;
Label3.Text = sql;
}
}至此,Gridview在编辑模板中添加DropdownList,并更新数据库完成。谢谢各位老师,回答都有分
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;public partial class gridview_GridViewUp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridViewBind();
}
} protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridViewBind();
} private void GridViewBind()
{
string connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
string SqlStr = "Select a.*,b.description FROM test01 a,xueli b where a.xueli=b.code and a.id<1000 and a.id>200";
DataSet ds = new DataSet(); try
{
SqlConnection conn = new SqlConnection(connStr);
if (conn.State.ToString() == "Closed") conn.Open();
SqlDataAdapter da = new SqlDataAdapter(SqlStr, conn);
da.Fill(ds, "test01");
if (conn.State.ToString() == "Open") conn.Close(); GridView1.DataSource = ds.Tables[0].DefaultView;
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write("数据库错误,错误原因:" + ex.Message);
Response.End();
}
} protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (((DropDownList)e.Row.FindControl("DDLXueli")) != null)
{
DropDownList ddlxueli = (DropDownList)e.Row.FindControl("DDLXueli"); // 生成 DropDownList 的值,绑定数据
string connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
string SqlStr = "Select * from xueli";
DataSet ds = new DataSet(); SqlConnection conn = new SqlConnection(connStr);
if (conn.State.ToString() == "Closed") conn.Open();
SqlDataAdapter da = new SqlDataAdapter(SqlStr, conn);
da.Fill(ds, "xueli");
if (conn.State.ToString() == "Open") conn.Close(); ddlxueli.DataSource = ds.Tables[0].DefaultView;
ddlxueli.DataTextField = "description";
ddlxueli.DataValueField = "code";
ddlxueli.DataBind();
// // 选中 DropDownList
ddlxueli.SelectedValue = ((HiddenField)e.Row.FindControl("HDFXueli")).Value;
//
}
} protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GridViewBind();
}
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GridViewBind();
} protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
string id = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
string card = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TBCard")).Text;
string xueli = ((DropDownList)GridView1.Rows[e.RowIndex].FindControl("DDLXueli")).SelectedValue;
string price = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TBPrice")).Text; string connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
string SqlStr = "update test01 set card='" + card + "',xueli='" + xueli + "',price='" + price + "' where id=" + id; try
{
SqlConnection conn = new SqlConnection(connStr);
if (conn.State.ToString() == "Closed") conn.Open();
SqlCommand comm = new SqlCommand(SqlStr, conn);
comm.ExecuteNonQuery();
comm.Dispose();
if (conn.State.ToString() == "Open") conn.Close(); GridView1.EditIndex = -1;
GridViewBind();
}
catch (Exception ex)
{
Response.Write("数据库错误,错误原因:" + ex.Message);
Response.End();
}
} protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
string id = GridView1.DataKeys[e.RowIndex].Values[0].ToString();
string connStr = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
string SqlStr = "delete from test01 where id=" + id; try
{
SqlConnection conn = new SqlConnection(connStr);
if (conn.State.ToString() == "Closed") conn.Open();
SqlCommand comm = new SqlCommand(SqlStr, conn);
comm.ExecuteNonQuery();
comm.Dispose();
if (conn.State.ToString() == "Open") conn.Close(); GridView1.EditIndex = -1;
GridViewBind();
}
catch (Exception ex)
{
Response.Write("数据库错误,错误原因:" + ex.Message);
Response.End();
}
}
}sql server2000生成表代码:
Create TABLE [dbo].[test01] (
[id] [decimal](18, 0) IDENTITY (1, 1) NOT NULL ,
[name] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[card] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[xueli] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
[price] [decimal](18, 0) NULL ,
[createdate] [datetime] NULL
) ON [PRIMARY]
GOAlter TABLE [dbo].[test01] ADD
CONSTRAINT [DF_test01_createdate] DEFAULT (getdate()) FOR [createdate],
CONSTRAINT [PK_test01] PRIMARY KEY CLUSTERED
(
[id]
) ON [PRIMARY]
GO
Create TABLE [dbo].[xueli](
[id] [int] IDENTITY(1,1) NOT NULL,
[code] [int] NULL,
[description] [nvarchar](50) COLLATE Chinese_PRC_CI_AS NULL,
CONSTRAINT [PK_xueli] PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]