在我的datagridview中選擇一行時,我希望我的資料庫中的日期顯示在我的應用程式中的DateTimePicker上。
但是我遇到了一個錯誤,它告訴我'String was not recognized as a valid DateTime.'
由于MySQL采用'yyy-MM-dd'格式,我將我的DateTimePicker格式改為相同。
我試著將DataGridView的值提取為一個字串,發現我得到的格式是"dd-MM-yyy hh:MM:ss t"
我應該如何解決?
我應該如何解決?
private void dtv_dis1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)。
{
txt_id.Text = dtv_dis1.SelectedRows[0].Cells[0].Value.ToString()。
txt_amt.Text = dtv_dis1.SelectedRows[0].Cells[6].Value.ToString()。
txt_remarks.Text = dtv_dis1.SelectedRows[0].Cells[5].Value.ToString()。
//Error with date0].Cells[1].Value.ToString()。
dtp_date.Value = DateTime.ParseExact(date, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) 。
//textBox1.Text = dtv_dis1.SelectedRows[0].Cells[1].Value.ToString();
tot = dtv_dis1.SelectedRows[0].Cells[2].Value.ToString()。
mop = dtv_dis1.SelectedRows[0].Cells[4].Value.ToString()。
cur = dtv_dis1.SelectedRows[0].Cells[3].Value.ToString()。
if (tot == "domestic")
{
rb_dom.Checked = true;
}
else; }
{
rb_in.Checked = true;
}
if (mop == "Cash"/span>)
{
rb_csh.Checked = true;
}
else if (mop == "Credit Card")
{
rb_cc.Checked = true;
}
else; }
{
rb_nb.Checked = true;
}
if (cur == "Doller")
{
rb_doller.Checked = true;
}
else if (cur == "Euro")
{
rb_euro.Checked = true;
}
else; }
{
rb_Rupees.Checked = true;
}
}
uj5u.com熱心網友回復:
如果網格的資料源是一個DataTable,并且 "Date "列的型別是一個DateTime的型別,那么,應該沒有必要去 "決議 "這個日期。
簡單地從資料源中抓取 "資料 "行,然后直接從單元格中抓取DateTime值...類似于...
if (dtv_dis1.CurrentRow != null) {
DataRowView drv = (DataRowView)dtv_dis1.CurrentRow.DataBoundItem;
dtp_date.Value = (DateTime)drv["Date"/span>]。
正如所評論的,如果列的型別是string型別......那么我建議你把它改為DateTime型別。
uj5u.com熱心網友回復:
一個建議,將資料庫資料加載到一個DataTable或List<T>然后使用一個BindingSource來分配DataTable或List<T>。
給DataTimePicker添加一個DataBinding,設定Format屬性為Custom,設定CustomFormat為yyyy-MM-dd。
如果使用List<T>并希望反映DataGridView中的變化,在代表T的類中實作INotifyPropertyChanged介面。
有一個List<T>和BindingSource的怪癖來反映源的變化,所以訂閱DateTimePicker的ValueChanged事件并設定DateTime列的值。
下面的截圖在DataGridView中顯示了日期,并有一個自定義的DataGridView列,其中出生日期與DateTimePicker是同步的。
一般來說,人們通常不希望通過單元格來訪問 DataGridView 中的資料,而是如上文所述,通過上述 BindingSource 中的 DataSource 來訪問。
要通過BindingSource獲取DataGridView中的當前行,首先要斷定.Current屬性不是空的,如果不是空的,則Current的型別,例如DataTable的DataRow,list的class型別。
在下面,資料源是一個使用Person1類的串列,從上面顯示的DataGridView中獲得當前行資訊。
private void CurrentPersonButton_Click(object sender, EventArgs e)。
{
if (_bindingSource is null || _bindingSource.Current is null) return;
var current = (Person1)_bindingSource.Current;
MessageBox.Show(
$"{current.FirstName} {current.LastName}
"
$"{current.BirthDate.Value:yyyy-MM-dd}")。)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/323083.html
標籤:
下一篇:函式只回傳輸入變數的第一個值


