我在尝试从下拉列表中选择日期时遇到此错误,一旦选择了日期,它应该根据下拉列表值在GridView中显示数据。这是使用'Where'语句等于所选索引的值来实现的。
我知道日期显示在下拉列表中的方式存在问题,而不是它们在数据库中保存的方式。所以我试图在下拉列表中将格式从dd / mm / yyyy交换到yyyy / mm / dd,看看是否能解决问题。但我似乎无法让它发挥作用。
有人可以推荐修复此问题吗?
下拉列表选择的索引更改C#:
protected void DropDownList2_SelectedIndexChanged(object sener, EventArgs e)
{
String query = "SELECT Stock_Take.Username, Item.ItemID, Item.ItemDesc, Stock_Take_Item.BarQuantity, Stock_Take_Item.StorageQuantity, Stock_Take.StockTakeIDNew FROM Item INNER JOIN Stock_Take_Item ON Item.ItemID = Stock_Take_Item.ItemID INNER JOIN Stock_Take ON Stock_Take_Item.StockTakeIDNew = Stock_Take.StockTakeIDNew where Stock_Take.Username = @USER AND Stock_Take.StockDate = @DATE";
SqlConnection con = new SqlConnection(@"Data Source=(local)\;Initial Catalog=SmallBatch;Integrated Security=True;");
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("@USER", SqlDbType.VarChar).Value = DropDownList1.SelectedValue;
cmd.Parameters.Add("@DATE", SqlDbType.DateTime).Value = DropDownList2.SelectedValue;
// DateTime date = Convert.ToDateTime(DropDownList2.SelectedValue.ToString());
SqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
con.Close();
}
将日期从数据库绑定到下拉列表C#代码:
private void BindDropDownList2(String field)
{
DataTable dataTable = new DataTable();
SqlConnection con = new SqlConnection(@"Data Source=(local)\;Initial Catalog=SmallBatch;Integrated Security=True;");
try
{
con.Open();
String Query = "Select StockDate, StockTakeIDNEW from Stock_Take WHERE Username = @Value1";
SqlCommand sqlCmd = new SqlCommand(Query, con);
sqlCmd.Parameters.AddWithValue("@Value1", field);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dataTable);
if (dataTable.Rows.Count > 0)
{
DropDownList2.DataSource = dataTable;
DropDownList2.DataTextField = "StockDate";
DropDownList2.DataValueField = "StockTakeIDNew";
// DropDownList2.DataTextFormatString = "(yyyy/MM/dd}";
DropDownList2.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error";
msg += ex.Message;
*我还有另一个下拉列表,用户从中选择一个用户名,进而影响DropDownList2中显示的日期
答案 0 :(得分:4)
下面:
cmd.Parameters.Add("@DATE", SqlDbType.DateTime).Value = DropDownList2.SelectedValue;
首先手动解析值,因此它是DateTime
:
var date = DateTime.Parse(DropDownList2.SelectedValue); // TODO: replace with format etc
cmd.Parameters.Add("@DATE", SqlDbType.DateTime).Value = date;