【发布时间】:2022-12-10 16:40:31
【问题描述】:
在我的 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 );
}
}
}
更新:我已经更新了代码,我意识到我需要连接表,并且通过连接这些表我可以更好地访问日期。日期不为空,只是当天根本没有输入。在用户输入结果之前,该日期根本不存在于数据库中。
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 );
}
}
}
【问题讨论】:
-
您的代码为查询结果中的每条记录创建一个新按钮。这里哪里有约会?
-
@RomanRyzhiy 编辑了我的问题以便更好地理解。
-
“没有为今天的日期 (DateTime.Now) 输入日期”你的意思是
DateTime.Today而不是DateTime.Now?! -
@TimSchmelter 这是正确的,对编码来说还是相当新的。
-
ID 获取整行值,包括日期的值。
item.SubItems[5].Text是该行的 ID。