在我的Sql表中,当输入一个值时,日期也随之记录下来。问题是,我想显示所有没有为今天的日期(DateTime.Today)输入日期的值(在我的例子中是动态创建的按钮)。如果该条目甚至没有为当天添加,我该如何做呢?
编辑:日期在SQL表中,但也在一个列表视图中,其中填充了来自SQL表的数据,以便于访问。按钮应仅显示为那些没有输入今天日期的按钮。
public void load()
{
foreach (ListViewItem item in ListView.Items)
{
//item.SubItems[5].Text is row's ID
SqlConnection conn = new SqlConnection(connstring);
string strsql = "SELECT ID from Table1 WHERE ID = '" + item.SubItems[5].Text + "'";
SqlCommand cmd = new SqlCommand(strsql, conn);
SqlDataReader reader = null;
cmd.Connection.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
System.Windows.Forms.Button test1Button = new System.Windows.Forms.Button();
test1Button.Click+= new EventHandler(button1ButtonClick);
test1Button .Text = reader["ID"].ToString();
test1Button .Size = new System.Drawing.Size(120, 38);
this.Controls.Add(test1Button );
flowLayoutPanel.Controls.Add(test1Button );
System.Windows.Forms.Button test2Button = new System.Windows.Forms.Button();
test2Button Button.Click += new EventHandler(LabelBtn_Click);
test2Button Button.Text = reader["ID"].ToString();
test2Button Button.BackColor = Color.DarkRed;
test2Button Button.ForeColor = Color.White;
test2Button Button.Size = new System.Drawing.Size(120, 38);
this.Controls.Add( test2Button );
flowLayoutPanel2.Controls.Add( test2Button );
}
}
}
***UPDATE:***我已经更新了代码,我意识到我需要连接表,通过这些表的连接,我可以更好地访问日期。日期不是空的,它们只是根本没有输入当天的日期。在用户输入结果之前,日期根本不存在于数据库中。
public void load()
{
foreach (ListViewItem item in ListView.Items)
{
SqlConnection conn = new SqlConnection(connstring);
string strsql = "SELECT * from Table1 AS t1 INNER JOIN Table2 AS t2 ON t1.[Table1 _ID] = t2.[Table2 _ID] WHERE Convert(Date, yourDateColumn) > Convert(Date, CURRENT_TIMESTAMP)";
SqlCommand cmd = new SqlCommand(strsql, conn);
SqlDataReader reader = null;
cmd.Connection.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
System.Windows.Forms.Button test1Button = new System.Windows.Forms.Button();
test1Button .Click += new EventHandler(button1ButtonClick);
test1Button .Text = reader["ID"].ToString();
test1Button .Size = new System.Drawing.Size(120, 38);
this.Controls.Add(test1Button );
flowLayoutPanel.Controls.Add(test1Button );
System.Windows.Forms.Button test2Button = new System.Windows.Forms.Button();
test2Button .Click += new EventHandler(LabelBtn_Click);
test2Button .Text = reader["ID"].ToString();
test2Button .BackColor = Color.DarkRed;
test2Button .ForeColor = Color.White;
test2Button .Size = new System.Drawing.Size(120, 38);
this.Controls.Add(test2Button );
flowLayoutPanel2.Controls.Add(test2Button );
}
}
}
1条答案
按热度按时间wydwbb8l1#
首先,你应该避免这样构造你的查询,因为这样会给你的应用带来安全风险。在这里考虑使用AddWithValue方法:https://learn.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlparametercollection.addwithvalue?view=dotnet-plat-ext-7.0
此外,如果您说日期在数据库中,只需在查询中提取它,我似乎无法理解,因为在我看来,您目前只提取ID,但基于ID ...最好这样做:
这样,您就可以只从表中选择日期不是今天日期的行。
而且,您似乎要添加两次按钮,一次添加到窗体,一次添加到flowLayoutPanel,我认为这是不必要的,只需将其添加到面板即可。