c# - 如果数据网格视图中的其他值为空
问题描述
使用 c# winforms 和 sqlite
我想从数据集中插入到我的数据库中。这些列是名称、开始日期、结束日期。日期和结束日期列的数据格式都错误,M/dd/yyyy 所以我将其转换为string startdate = Convert.ToDateTime(startdatetime).ToString("dd/M/yyyy");
问题是开始日期和结束日期列中有空值,所以我无法转换所有内容首先检查空单元格。所以我不确定要为查询输入什么,因为如果单元格为空,插入 startdatetime 会将其置于错误的格式中,而插入 startdate 会导致错误。我计划在完成后将其更改为更安全并防止 sqlinjection。
string startdatetime = dataGridView1.SelectedRows[0].Cells["Start Date"].Value.ToString();
string enddatetime = dataGridView1.SelectedRows[0].Cells["End Date"].Value.ToString();
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (string.IsNullOrEmpty(cell.Value as string))
{
string txtQuery = "insert into CertDB(DateAttended, EndDate) values ('" + startdatetime + "', '" + enddatetime + "')";
ExecuteQuery(txtQuery);
}
else
{
string startdate = Convert.ToDateTime(startdatetime).ToString("dd/M/yyyy");
string enddate = Convert.ToDateTime(enddatetime).ToString("dd/M/yyyy");
string expiry = Convert.ToDateTime(expirytime).ToString("dd/M/yyyy");
string txtQuery = "insert into CertDB(DateAttended, EndDate) values ('" + startdate + "', '" + enddate + "')";
ExecuteQuery(txtQuery);
}
}
}
解决方案
.ToString()
不会处理null
所以必须使用Convert.ToString()
string startdatetime = Convert.ToString(dataGridView1.SelectedRows[0].Cells["Start Date"].Value);
string enddatetime = Convert.ToString(dataGridView1.SelectedRows[0].Cells["End Date"].Value);
foreach (DataGridViewRow row in dataGridView1.Rows)
{
foreach (DataGridViewCell cell in row.Cells)
{
if (string.IsNullOrEmpty(cell.Value as string))
{
string txtQuery = "insert into CertDB(DateAttended, EndDate) values ('" + startdatetime + "', '" + enddatetime + "')";
ExecuteQuery(txtQuery);
}
else
{
string startdate = string.IsNullOrWhiteSpace(startdatetime) ? DBNull.Value : Convert.ToDateTime(startdatetime).ToString("dd/M/yyyy");
string enddate = string.IsNullOrWhiteSpace(enddatetime) : DBNull.Value : Convert.ToDateTime(enddatetime).ToString("dd/M/yyyy");
string expiry = string.IsNullOrWhiteSpace(expirytime) ? DBNull.Value : Convert.ToDateTime(expirytime).ToString("dd/M/yyyy");
string txtQuery = "insert into CertDB(DateAttended, EndDate) values ('" + startdate + "', '" + enddate + "')";
ExecuteQuery(txtQuery);
}
}
}
同样DateAttended
,EndDate
列应该nullable
在DataBase
. 您还可以阅读更多关于.ToString()
和Convert.ToString()
推荐阅读
- c# - 在c#中对列表进行排序(自定义排序规则)
- c++ - 嵌套模板显式特化
- c - 汇编优化函数调用,允许从函数中取出常量?
- asp.net-mvc - 将选定的单选按钮值传递给控制器 C# MVC
- vb.net - 如何检查电子邮件地址 smtp 主机?
- java - Selenium Standalone 已退出,代码为 1 / 系统找不到指定的路径
- kubernetes - Prometheus Pods 在 grafana 中重启
- sublimetext3 - 如何选择不同的评论标记?
- python - def 函数在每个 (while) 循环中重复两次,即使我每次只调用一次
- flask - Flask WTForms:为什么我上传文件的 POST 请求没有发送文件数据?