我正在尝试从下拉列表中选择动态数据并查看所选项目的详细信息。使用数据库中的数据填充下拉列表没有问题。但是,当我选择一些项目时,它不会显示细节。
在我的表示层中,选择下拉列表项时:
protected void ddlScheduleList_SelectedIndexChanged(object sender, EventArgs e)
{
string address = ddlScheduleList.SelectedItem.ToString();
Distribution scheduledIndv = new Distribution();
scheduledIndv = packBLL.getDistributionDetail(address);
if (scheduledIndv == null)
{
Console.Out.WriteLine("Null");
}
else
{
tbScheduleDate.Text = scheduledIndv.packingDate.ToString();
tbBeneficiary.Text = scheduledIndv.beneficiary;
}
}
在我的业务逻辑层中,我获取所选地址并将其传递给数据访问层:
public Distribution getDistributionDetail(string address)
{
Distribution scheduledIndv = new Distribution();
return scheduledIndv.getDistributionDetail(address);
}
在我的数据访问层中,我已经测试了SQL语句。它给了我想要的东西。但它只是不会出现在网页上。
public Distribution getDistributionDetail(string address)
{
Distribution distributionFound = null;
using (var connection = new SqlConnection(FoodBankDB.GetConnectionString())) // get your connection string from the other class here
{
SqlCommand command = new SqlCommand("SELECT d.packingDate, b.name FROM dbo.Distributions d " +
" INNER JOIN dbo.Beneficiaries b ON d.beneficiary = b.id " +
" WHERE b.addressLineOne = '" + address + "'", connection);
connection.Open();
using (var dr = command.ExecuteReader())
{
if (dr.Read())
{
DateTime packingDate = DateTime.Parse(dr["packingDate"].ToString());
string beneficiary = dr["beneficiary"].ToString();
distributionFound = new Distribution(packingDate, beneficiary);
}
}
}
return distributionFound;
}
我在另一个分离的类中执行Reader方法:
public static string connectionString = Properties.Settings.Default.connectionString;
public static string GetConnectionString()
{
return connectionString;
}
public static SqlDataReader executeReader(string query)
{
SqlDataReader result = null;
System.Diagnostics.Debug.WriteLine("FoodBankDB executeReader: " + query);
SqlConnection connection = new SqlConnection(connectionString);
SqlCommand command = new SqlCommand(query, connection);
connection.Open();
result = command.ExecuteReader();
connection.Close();
return result;
}
我想知道出了什么问题。是关于(!IsPostBack)还是?
提前致谢。
答案 0 :(得分:1)
您发现了错误,但为了避免Sql Injection,请修改您的代码:
SqlCommand command = new SqlCommand("SELECT d.packingDate, b.name FROM dbo.Distributions d " +
" INNER JOIN dbo.Beneficiaries b ON d.beneficiary = b.id " +
" WHERE b.addressLineOne = @address", connection);
command.Parameters.AddWithValue("@address", address);