[英]How to Reuse Logic Without Copy/Pasting Blocks of Code - C#
My project reuses the code below multiple times with only a few variables changing. 我的项目多次更改了下面的代码,仅更改了几个变量。 I've noted the values that change with eg ***value***.
我注意到,例如*** value ***会改变的值。
if (comboBox1.Text == ***"Most recent first"***)
{
string dgvconn = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\CW\CW\bin\Debug\Database1.mdf;Integrated Security=True";
string sql = "select * from Records where UserID = @userID Order By ***Date Desc***";
SqlConnection connection = new SqlConnection(dgvconn);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
dataadapter.SelectCommand.Parameters.AddWithValue("@userID", currentUserID);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Records");
connection.Close();
recordsDataGridView.DataSource = ds;
recordsDataGridView.DataMember = "Records";
}
How can I use this same logic, with different values, without copying and pasting the if statement multiple times? 如何在不多次复制和粘贴if语句的情况下使用具有不同值的相同逻辑?
Sounds to me you want something like: 在我看来,您想要这样的东西:
private void foo(string matchText, string sortBy) {
if (comboBox1.Text == matchText)
{
string dgvconn = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\n0740572\Projects\CW\CW\bin\Debug\Database1.mdf;Integrated Security=True";
string sql = "select * from Records where UserID = @userID Order By " + sortBy;
SqlConnection connection = new SqlConnection(dgvconn);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, connection);
dataadapter.SelectCommand.Parameters.AddWithValue("@userID", currentUserID);
DataSet ds = new DataSet();
connection.Open();
dataadapter.Fill(ds, "Records");
connection.Close();
recordsDataGridView.DataSource = ds;
recordsDataGridView.DataMember = "Records";
}
}//foo
//Call the method
foo("Most recent first", "Date DESC");
foo("Most recent last", "Date");
foo("By Username", "User");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.