[英]How do I populate an ASPX C# Form with multiple dropdowns from different related tables?
這是我為公司建立網站的第一次嘗試。 我基本上有一個帶有3個表的數據庫。 結構如下。
tblSiteDataEntryForm
ID
網站名稱
siteType
siteSubType
tblPrimaryTypes
ID
主要類型
tblSubTypes
ID
PrimaryTypeID
子類型
員工將使用簡單的表單在主表中創建新的數據庫條目。 我有這個表格在工作。 第二種形式將用於更新主表。 在更新表單上,我有一個下拉列表,可使用主數據庫上的選擇查詢來獲取其值。 然后將基於主表中的行數據填充主類型和子類型的下拉列表。 主要類型下拉列表正在運行,但是子類型不斷拋出錯誤。 “ ddlSubType的SelectedValue無效,因為它在項目列表中不存在。參數名稱:value”
這是我的代碼。 任何幫助將不勝感激。
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class ddef_update : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadInfo();
}
}
protected void LoadInfo()
{
SqlConnection connection;
SqlCommand command;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string firstSql = null;
string secondSql = null;
string thirdSql = null;
DataTable sites = new DataTable();
DataTable types = new DataTable();
DataTable subtypes = new DataTable();
firstSql = "SELECT ID, siteName FROM tblSiteDataEntryForm";
secondSql = "SELECT ID, PrimaryType FROM tblPrimaryTypes";
thirdSql = "SELECT ID, SubType FROM tblSubTypes";
connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConsString"].ToString());
{
connection.Open();
command = new SqlCommand(firstSql, connection);
adapter.SelectCommand = command;
adapter.Fill(sites);
ddlSiteName.DataSource = sites;
ddlSiteName.DataTextField = "siteName";
ddlSiteName.DataValueField = "ID";
ddlSiteName.DataBind();
adapter.SelectCommand.CommandText = secondSql;
adapter.Fill(types);
ddlPrimaryType.DataSource = types;
ddlPrimaryType.DataTextField = "PrimaryType";
ddlPrimaryType.DataValueField = "ID";
ddlPrimaryType.DataBind();
adapter.SelectCommand.CommandText = thirdSql;
adapter.Fill(subtypes);
ddlSubType.DataSource = subtypes;
ddlSubType.DataTextField = "SubType";
ddlSubType.DataValueField = "ID";
ddlSubType.DataBind();
adapter.Dispose();
command.Dispose();
connection.Close();
}
}
protected void ddlSiteName_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = ddlSiteName.SelectedItem.Value;
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConsString"].ToString());
using (connection)
{
SqlCommand command = new SqlCommand("SELECT * FROM tblSiteDataEntryForm WHERE ID= @ID", connection);
command.Parameters.AddWithValue("@ID", selected);
command.CommandType = CommandType.Text;
connection.Open();
SqlDataReader reader = command.ExecuteReader();
using (reader)
{
if (reader.HasRows)
{
reader.Read();
ddlPrimaryType.Text = reader["siteType"].ToString();
ddlSubType.Text = reader["siteSubType"].ToString();
}
}
}
}
}
我能夠解決問題。 主表中的siteSubType包含文本值。 將其更改為整數,一切正常
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.