我是 ASP.NET 的新手,一直在尝试使下拉列表在 DetailsView 中正常工作,但到目前为止还没有运气。我正在努力实现这一目标,非常感谢有人可以帮助我。
我得到的一个错误是:
Eval()、XPath() 和 Bind() 等数据绑定方法只能在数据绑定控件的上下文中使用。
我的 DetailsView 中有这段代码:
<EditItemTemplate>
<asp:DropDownList id="VendorName"
datasourceid="VendorSqlDataSource"
AutoPostBack="true"
datatextfield="VendorName"
DataValueField="VendorID"
SelectedValue='<%# Bind("VendorID") %>'
runat="server"
OnSelectedIndexChanged="ddlCategory_SelectedIndexChanged" />
<asp:SqlDataSource ID="VendorSqlDataSource"
ConnectionString="<%$Connectionstrings:ConnectionString%>"
SelectCommand="SELECT VendorID, VendorName from MDF_Vendor"
runat="server">
</asp:SqlDataSource>
</EditItemTemplate>
<EditItemTemplate>
<asp:DropDownList id="VendorBUName"
datasourceid="VendorBUSqlDataSource"
datatextfield="VendorBUName"
DataValueField="VendorBUID"
SelectedValue='<%# Bind("VendorBUID") %>'
runat="server"/>
<asp:SqlDataSource ID="VendorBUSqlDataSource"
runat="server"
ConnectionString="<%$Connectionstrings:ConnectionString%>"
selectcommand="SELECT VendorBUID, VendorBUName
from MDF_VendorBU
Where VendorID = @VendorID"
<SelectParameters>
<asp:Parameter Name="VendorID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</EditItemTemplate>
在我的代码背后,我有此代码可以重建Vendorname选择时的VendorBuname dropdownlist列表。
protected void ddlVendor_SelectedIndexChanged
(object sender, EventArgs e)
{
DropDownList ddlVendor =
(DropDownList)DetailsView1.FindControl("VendorName");
DropDownList ddlVendorBU =
(DropDownList)DetailsView1.FindControl("VendorBUName");
if (ddlVendorBU != null)
{
Response.Write("SelectChanged");
int VendorID = Convert.ToInt32(ddlVendor.SelectedValue.ToString());
Response.Write("VendorID: " + VendorID);
ddlVendorBU.Items.Clear();
string strConn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(strConn);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT VendorBUID, VendorBUName FROM dbo.MDF_VendorBU WHERE VendorID = @VendorID";
cmd.Parameters.AddWithValue("@VendorID", VendorID);
DataSet objDs = new DataSet();
SqlDataAdapter dAdapter = new SqlDataAdapter();
dAdapter.SelectCommand = cmd;
con.Open();
dAdapter.Fill(objDs);
con.Close();
if (objDs.Tables[0].Rows.Count > 0)
{
foreach (DataRow dr in objDs.Tables[0].Rows)
{
ddlVendorBU.Items.Insert(0, new ListItem( (dr["VendorBUName"]).ToString(), "-1") );
}
ddlVendorBU.DataBind(); //<-- Problem HERE can not rebind it.
}
}
}
到目前为止,这在 DetailsView 中有效。我单击编辑,这两个下拉列表选择了正确的值。当我在 VendorName ddl 中选择另一个供应商时,它会刷新 VendorBUName 列表。伟大的!但是,当我尝试 ddlVendorBU.DataBind(); 重新绑定 VendorBUName 列表,它给出了上面的错误。如果删除它,它不会更新 VendorBUName 的记录,因为它没有绑定到该字段。
我完全被卡住了,如果有人可以帮忙。提前致谢!