我正在學習代碼,所以我有一個問題,我想將日期從 datagridview 顯示到文本框,但我不知道如何在沒有時間的情況下顯示它。感謝你們。

public partial class StackoverFlowForm : Form
{
private readonly BindingSource _bindingSource = new();
private readonly string _dateFormat = "dd/MM/yyyy";
public StackoverFlowForm()
{
InitializeComponent();
_bindingSource.DataSource = Mocked.Table();
dataGrid.DataSource = _bindingSource;
dataGrid.Columns["DateItem"]!.DefaultCellStyle.Format = _dateFormat;
}
private void GetStartDateButton_Click(object sender, EventArgs e)
{
if (dataGrid.CurrentRow!.Cells["DateItem"].Value.IsNull())
{
txtDate.Text = "";
}
else
{
var dateTime = (((DataRowView)_bindingSource.Current)!)
.Row.Field<DateTime>("DateItem");
txtDate.Text = dateTime.ToString(_dateFormat);
}
}
}
#region Place these classes in separate files
public static class LanguageExtensions
{
public static bool IsNull(this object sender)
=> sender == null || sender == DBNull.Value || Convert.IsDBNull(sender);
}
public class Mocked
{
public static DataTable Table()
{
var dt = new DataTable();
dt.Columns.Add(new DataColumn()
{
ColumnName = "Id",
DataType = typeof(int),
AutoIncrement = true,
AutoIncrementSeed = 1,
ColumnMapping = MappingType.Hidden
});
dt.Columns.Add(new DataColumn() { ColumnName = "FirstName", DataType = typeof(string) });
dt.Columns.Add(new DataColumn() { ColumnName = "LastName", DataType = typeof(string) });
dt.Columns.Add(new DataColumn() { ColumnName = "DateItem", DataType = typeof(DateTime) });
dt.Rows.Add(null, "Jeanine", "Abbott",
new DateTime(2018, 2, 12, 8, 0, 0));
dt.Rows.Add(null, "Lester", "Lam",
new DateTime(2018, 9, 8, 9, 0, 0));
dt.Rows.Add(null, "Claire", "Cowan",
new DateTime(2018, 1, 1, 10, 0, 0));
dt.Rows.Add(null, "Karen", "Payne",
new DateTime(2022, 1, 1, 10, 0, 0));
return dt;
}
}
#endregion
有人提到使用DateOnly,但沒有任何收獲。
private void GetStartDateButton_Click(object sender, EventArgs e)
{
if (dataGrid.CurrentRow!.Cells["DateItem"].Value.IsNull())
{
txtDate.Text = "";
}
else
{
var dateTime = (((DataRowView)_bindingSource.Current)!)
.Row.Field<DateTime>("DateItem");
txtDate.Text = DateOnly.FromDateTime(dateTime).ToString(_dateFormat);
}
}
uj5u.com熱心網友回復:
您正在嘗試應用字串上不存在的 ToString 方法的多載。
您必須首先將初始字串轉換為 DateTime,如下所示:
if(!string.IsNullOrWhiteSpace(dataGrid.Cells[2].Value.ToString()) && DateTime.TryParse(dataGrid.Cells[2].Value.ToString(), out DateTime date))
{
txtDate.Text = date.ToString("dd/MM/yyyy");
}
ToString 的多載可以通過將格式作為引數來使用
uj5u.com熱心網友回復:
您可以嘗試使用 DateOnly。
https://learn.microsoft.com/en-us/dotnet/api/system.dateonly?view=net-6.0
或使用以下命令轉換為所需格式輸出的字串:
ToString(dd/MM/yyyy)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/522144.html
標籤:C#表格
