我试图刷新ComboBox中可用的天数。这是我创建的按钮,其中mindate和maxdate从DateTime Picker获取它们的值,Dia是DataGridViewComboBoxColumn但它不起作用。任何人都可以帮我找到问题的根源以及如何解决它。或者,如果你知道另一种方式,它也会有所帮助。 编辑:我说的按钮是button3。
public partial class InserirViagens : Form
{
private DateTime mindate;
private DateTime maxdate;
public InserirViagens()
{
InitializeComponent();
textBox1.Text = (Dados.agência.Viagens.Count + 1).ToString();
textBox1.Enabled = false;
dateTimePicker1.MinDate = DateTime.Now;
dateTimePicker2.MinDate = DateTime.Now;
mindate = dateTimePicker1.Value;
maxdate = dateTimePicker2.Value;
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
int cod = int.Parse(textBox1.Text);
string des = textBox2.Text;
double preço = double.Parse(textBox3.Text);
DateTime inicio = dateTimePicker1.Value;
DateTime fim = dateTimePicker2.Value;
int contalinhas = (int)dataGridView1.RowCount-1;
if (inicio<=fim)
{
Viagem v = new Viagem(cod, des, preço, inicio, fim);
Dados.agência.Viagens.Add(cod, v);
MessageBox.Show("Viagem Inserida com sucesso!\nContém " + contalinhas + " actividades.\n"+ Dados.dados.Viagens.Count + " Viagens existentes");
this.Close();
}
else MessageBox.Show("Data de fim inválida!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
catch(FormatException)
{
MessageBox.Show("Erro de formatação!", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
mindate = dateTimePicker1.Value;
}
private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
{
maxdate = dateTimePicker2.Value;
}
private void button3_Click(object sender, EventArgs e)
{
Dia.Items.Clear();
while (mindate.DayOfYear < maxdate.DayOfYear)
{
Dia.Items.Add(mindate.Day + "/" + mindate.Month + "/" + mindate.Year);
mindate.AddDays(1);
}
}
}
}
答案 0 :(得分:0)
Dia.Items.Clear();
while (mindate.DayOfYear < maxdate.DayOfYear)
{
Dia.Items.Add(mindate.Day + "/" + mindate.Month + "/" + mindate.Year);
mindatee.AddDays(1);
}
mindatee.AddDays(1);
不起作用。
AddDays方法信息
返回一个新的DateTime,它将指定的天数添加到 这个实例的价值。
因此它返回一个新的DateTime,并且不会更改旧的(在本例中为mindate)值。
<强>解决方案强>
在temp变量中保存mindate.AddDays(1)并将当前mindate替换为temp datetime值。
Dia.Items.Clear();
while (mindatee.DayOfYear < maxdatee.DayOfYear)
{
Dia.Items.Add(mindate.Day + "/" + mindate.Month + "/" + mindate.Year);
var tempDate = mindate.AddDays(1);
mindate = tempDate;
}
如果您不想使用临时变量,您也可以在一行代码中执行此操作:
mindate = mindate.AddDays(1);
答案 1 :(得分:0)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Btn_Click(object sender, EventArgs e)
{
DateTime minDate = Convert.ToDateTime(mindate.Value);
DateTime maxDate = Convert.ToDateTime(maxdate.Value);
foreach ( DataGridViewComboBoxColumn cmbCol in dataGridView1.Columns) {
cmbCol.Items.Clear();
while (minDate.Day < maxDate.Day) {
cmbCol.Items.Add($"{minDate.Day}/{minDate.Month}/{minDate.Year}");
minDate= minDate.AddDays(1);
}
}
}
}