を使用される同じコード私は、システムを作ってるんだと私は 私のコードが最適化されていませんが、それは私は私のコードの冗長性を軽減したい ここ 例複数回
を働いている私のコードに何かに気づきますこれは、私はこれは私がこれは私が更新する方法です
ry//Add
{
con.Open();
SqlCommand sc = new SqlCommand("INSERT INTO Category([Category]) VALUES(@Category)", con);
{
sc.Parameters.AddWithValue("@Category", txtCategory.Text);
sc.ExecuteNonQuery();
MessageBox.Show(txtCategory.Text + " is added");
txtCategory.Clear();
}
con.Close();
}
catch (SystemException ex)
{
MessageBox.Show(ex.ToString());
}
try//Refresh
{
dgvCategory.Rows.Clear();
SqlCommand sc = new SqlCommand("SELECT ID,Category FROM Category WHERE Active = 1", con);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Category", typeof(string));
dt.Load(reader);
for (int x = 0; x < dt.Rows.Count; x++)
{
string ID = dt.Rows[x].ItemArray[0].ToString();
string Category = dt.Rows[x].ItemArray[1].ToString();
string[] row = { ID, Category };
dgvCategory.Rows.Add(row);
}
con.Close();
}
catch (SystemException ex)
{
MessageBox.Show(ex.ToString());
}
追加する方法です
private void frmCategory_Load(object sender, EventArgs e)
{
//Populate
con.Open();
SqlCommand sc = new SqlCommand("SELECT ID,Category FROM Category WHERE Active = 1",con);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("ID",typeof(int));
dt.Columns.Add("Category",typeof(string));
dt.Load(reader);
for(int x = 0; x <dt.Rows.Count; x++)
{
string ID = dt.Rows[x].ItemArray[0].ToString();
string Category = dt.Rows[x].ItemArray[1].ToString();
string[] row = { ID,Category };
dgvCategory.Rows.Add(row);
}
con.Close();
}
ロードする方法です
try//Update
{
string ID = dgvCategory.SelectedCells[0].Value.ToString();
con.Open();
SqlCommand sc = new SqlCommand("UPDATE Category SET Category = '" + txtCategory.Text + "' WHERE ID = '" + ID + "'", con);
sc.ExecuteNonQuery();
MessageBox.Show(dgvCategory.SelectedCells[1].Value.ToString() + " is updated to " + txtCategory.Text);
con.Close();
}
catch (SystemException ex)
{
MessageBox.Show(ex.ToString());
}
try
{
dgvCategory.Rows.Clear();
SqlCommand sc = new SqlCommand("SELECT ID,Category FROM Category WHERE Active = 1", con);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(int));
dt.Columns.Add("Category", typeof(string));
dt.Load(reader);
for (int x = 0; x < dt.Rows.Count; x++)
{
string ID = dt.Rows[x].ItemArray[0].ToString();
string Category = dt.Rows[x].ItemArray[1].ToString();
string[] row = { ID, Category };
dgvCategory.Rows.Add(row);
}
con.Close();
}
catch (SystemException ex)
{
MessageBox.Show(ex.ToString());
}
が表示されます。私はいつも私のDGVをもう一度読み込むためにロードのコードを使用しています。それは私がリフレッシュする方法です。私はちょうどコードのブロックを作ることができて、LOADして、LOADを使ってLOADを使うことができるのだろうか?
メソッドにコードをリファクタリングし、メソッドを呼び出します。いくつかのものしか見えない場合は、それらのパラメータを渡してください。 – duffymo
ごめんなさい。私は今私のコードを入れます。 @duffymo –