使用组合框和文本框确定出生日期

时间:2018-08-07 20:29:05

标签: c#

我组合了2个文本框和文本框。不知道如何将字符串转换为日期时间。

string DOb  = $"{comboMM.SelectedValue}, {ComboDD.SelectedValue}, {txtYear.Text"";
string Query = "Insert into dbo.membertable(Given_Names, Last_Name, passport_No, Ctry_Origin, gender, M_status, DOb,MarAnn, Phone_No,Email,branch,Unit,H_address,city,states,Country,famdfrd_Name,famfrd_Number,famfrd_rship) Values('" + txtnames.Text + "','" + txtFamilyname.Text + "','" + txtPassport.Text + "','" + txtCountry.Text + "','" + ComboGender.SelectedItem + "','" + ComboMStatus.SelectedItem + "','" + DateB.Value.ToShortDateString() + "','" +  MarAnn + "','" + txtPhoneNo.Text + "','" + txtEmailAdd.Text + "','" + ComboBranch.SelectedItem + "','" + ComboUnit.SelectedItem + "','" + txtAddress.Text + "','" + txtCity.Text + "','" + ComboState.SelectedItem + "','" + ComboCountry.SelectedItem + "','" + txtrelative.Text + "','" + TxtRphone.Text + "','" + txtRelationship.Text + "');";

ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings["PottersDB"];
String connectionString = conSettings.ConnectionString;
try
{

    con = new SqlConnection(connectionString);
    con.Open();
    cmd = new SqlCommand(Query, con);
    dr  = cmd.ExecuteReader();
    MessageBox.Show("Member Successfully Added");
    Reset_Page();
    con.Close();
}

2 个答案:

答案 0 :(得分:1)

如注释中所建议,在查询中使用参数将简化代码。

请参阅以下代码作为示例。我添加了一些额外的注释,以建议对您提供的代码进行改进。

// Create a DateTime object from your controls, instead of a string representation.
var year = int.Parse(txtYear.Text);
var month = int.Parse(comboMM.SelectedValue);
var day = int.Parse(ComboDD.SelectedValue);
var dateOfBirth = new DateTime(year, month, day);

// Use parameters in your query instead of appending the string values
var query = "Insert into dbo.membertable(Given_Names, Last_Name, DOb, OtherFields) Values(@GivenNames, @LastName, @DOB, @OtherParameters);";

// Wrap your SqlConnection and SqlCommand in using blocks to ensure they are disposed correctly.
var connString = ConfigurationManager.ConnectionStrings["PottersDB"].ConnectionString;
using (var conn = new SqlConnection(connString))
{
    conn.Open();

    using (var cmd = new SqlCommand(query, conn))
    {
        cmd.Parameters.AddWithValue("@GivenNames", txtnames.Text);
        cmd.Parameters.AddWithValue("@LastName", txtFamilyname.Text);
        cmd.Parameters.AddWithValue("@DOB", dateOfBirth);

        // As the query is just inserting, there's no need to create a data reader.
        cmd.ExecuteNonQuery();
    }
}

正如Avrohom Yisroel所述,DatePicker控件似乎更适合您的应用程序。它允许用户选择一个日期,您可以从对象的SelectedDate属性中访问该日期。这样可以节省您为年份创建一个TextBox以及为日/月创建两个ComboBox的麻烦。

答案 1 :(得分:0)

简单的答案是改用日期选择器。那就是他们的目的,那是用户的期望,它为您验证了输入,它为您提供了DateTime而不是您必须隐蔽的字符串...

还有更多,但是应该足够!