在C#Windows应用程序中帮助DateTimePicker。 [英] Help with DateTimePicker in C# Windows Application.
问题描述
我想将日期从 DateTimePicker添加到数据库表&还想从数据库表中检索日期到DateTimePicker 。
基本上,我的datagridview在每次操作时都会更新(插入,更新,删除) &安培;它有编辑按钮。当我点击编辑按钮时,datagridview行中的所有值都相应地设置为我的表单中的控件(标签,文本框)。
主表单代码:
I want to add date from DateTimePicker to database table & also want to retrieve date from database table to DateTimePicker.
Basically,My datagridview get updated at each operation(insert,update,delete) & it has edit button. when I click on edit button all the values from datagridview row are set to the controls in my form(label,textbox) correspondingly.
Main form code :
private void btnSAdd_Click(object sender, EventArgs e)
{
// to insert value in database I've passed all values to class
SavingsDetails sd = new SavingsDetails(lblSTId.Text,cmbSGID,cmbSMId,dtpInstallmentDate.Text,txtInstallmentAmt.Text);
sd.Add();
setSavingsGridView();
}
代码在SavingsDetails类:
code in SavingsDetails Class :
class SavingsDetails
{
protected int STId,MId,GId,Amt;
DateTime SDate;
Connection con;
public SavingsDetails(string _STId, int _GId, int _MId, DateTime _SDate, string _Amt)
{
con = new Connection();
STId = Convert.ToInt16(_STId);
GId = _GId;
MId = _MId;
SDate = _SDate;
Amt = Convert.ToInt32(_Amt);
}
public void Add()
{
con.Execute("insert into tblSavingsDetails(STId,STDate,GId,MId,SavingInstallment) values("+ STId +","+ SDate +","+ GId +","+ MId +","+ Amt +"");
}
从数据库检索到表单控件:
To retrieve from database to form controls :
private void dgvSavingsDetails_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 0) //code for setting values in controls on clicking edit image in gridview
{
btnSUpdate.Enabled = true;
lblSTId.Text = dgvSavingsDetails.Rows[e.RowIndex].Cells[2].Value.ToString();
cmbSGrpName.SelectedValue = dgvSavingsDetails.Rows[e.RowIndex].Cells[3].Value;
cmbSMName.SelectedValue = dgvSavingsDetails.Rows[e.RowIndex].Cells[4].Value;
dtpInstallmentDate.Text = dgvSavingsDetails.Rows[e.RowIndex].Cells[5].Value.ToString();
txtInstallmentAmt.Text = dgvSavingsDetails.Rows[e.RowIndex].Cells[6].Value.ToString();
}
else if (e.ColumnIndex == 1)
{
//code for deletion
}
}
请帮助。
Please Help.
推荐答案
尝试:
Try:
using (SqlCommand cmd = new SqlComand("INSERT INTO MyTable (myDateColumn) VALUES (@DT)", con))
{
cmd.Parameters.AddWithValue("@DT", myDateTimePicker.Value);
cmd.ExecuteNonQuery();
}
并且:
And:
using (SqlCommand cmd = new SqlComand("SELECT myDateColumn FROM MYTable", con))
{
SqlDataReader read = cmd.ExecuteReader();
while (read.Read())
{
DateTime dt = (DateTime) read["myDateColumn"];
...
}
}
我自己解决了这个问题。感谢您的帮助。
用 dtpInstallmentDate.Value.Date &替换 dtpInstallmentDate.Text 在Add()方法中,在插入查询的值中更新了 SDate.ToShortDateString()。
I've solved this myself. Thank you for your help.
Replaced dtpInstallmentDate.Text with dtpInstallmentDate.Value.Date & In Add() method, updated SDate.ToShortDateString() in values of insert query.
这篇关于在C#Windows应用程序中帮助DateTimePicker。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!