无法从DB Null或C#中的其他类型强制转换对象

时间:2018-10-31 13:46:07

标签: c#

每当我按下DataGridView上的“添加”按钮时,我在此行上都会出错。

DateTime PostedDate = Convert.ToDateTime(selectedRow.Cells[2].Value);
  

表中的日期时间不为空。

完整代码:

private void receivingTableDataGridView_SelectionChanged(object sender, 
EventArgs e)
{
    if (receivingTableDataGridView.SelectedCells.Count > 0)
    {
        int selectedrowindex = receivingTableDataGridView.SelectedCells[0].RowIndex;
        DataGridViewRow selectedRow = receivingTableDataGridView.Rows[selectedrowindex];
        DateTime PostedDate = Convert.ToDateTime(selectedRow.Cells[2].Value);
    }
}

2 个答案:

答案 0 :(得分:4)

使用可为空的DateTime,但值为null时Convert.ToDateTime返回说明。

<!-- HTML FORM -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="profile-form" method="post" action="submit_using_jQuery.php">
    <div class="form-group">
        <label for="inputTwitter">Twitter Link</label>
        <input name="Profile-twitter" type="text"  id="inputTwitter" placeholder="Twitter Link">
    </div>
    <div class="form-group">
        <label for="inputYouTube">YouTube Link</label>
        <input name="Profile-youTube" type="text"  id="inputYouTube" placeholder="YouTube Link"><br/>
    </div>
    <div class="form-group">
        <label for="bio">Bio</label>
        <textarea name="Profile-bio" id="bio"></textarea>
    </div>
    <div class="form-group">
        <label for="">Gender</label>
        <input type="radio" name="Profile-gender" value="male">Male
        <input type="radio" name="Profile-gender" value="female">Female
    </div>
    <div class="form-group">
        <label for="">Hobby</label>
        <input type="checkbox" name="Profile-hobby[cricket]">Cricket
        <input type="checkbox" name="Profile-hobby[football]">football
    </div>
    <button type="submit" id="Profile-submit">Profil aktualisieren</button>
</form>

答案 1 :(得分:2)

PostedDate应该是Nullable<DateTime>DateTime?),因为如果值为DbNull.Value,则可以为null。您可以使用以下代码进行检查:

DateTime? postedDate = null;
if(!System.Convert.IsDBNull(selectedRow.Cells[2].Value))
{
    postedDate = Convert.ToDateTime(selectedRow.Cells[2].Value);
}