首页 > 解决方案 > 如果数据网格视图中的其他值为空

问题描述

使用 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);
                }
            }
        }

标签: c#datagridview

解决方案


.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);
                }
            }
        }

同样DateAttendedEndDate列应该nullableDataBase. 您还可以阅读更多关于.ToString()Convert.ToString()


推荐阅读