1

C# Web アプリケーションに GridView コントロールがあります。私のグリッドビューには、 Select という ButtonField がありID="btnSelect"ます。基本的に、私の GridView コントロールには、クライアントの名、姓、住所、電話番号があり、対応する情報にはテキスト ボックスがあります。グリッドビューで選択ボタンを押す/起動すると、クライアント名をテキスト ボックスに入力したいのですが、それは成功しましたが、私のアプリケーションでは最大 6 つのクライアントを選択できます。私がこれを行っている方法よりも良い方法はありますか? コードは以下のとおりです。

 void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e)
 {
  int index = Convert.ToInt32(e.CommandArgument);
  GridViewRow row = GridView1.Rows[index];


  if(string.IsNullOrEmpty(txtName1.Text) && string.IsNullOrEmpty(txtLName1.Text) &&
     string.IsNullOrEmpty(txtAddr1.Text) && string.IsNullOrEmpty(txtPhone1.Text))
    {
      txtName1.Text=Server.HtmlDecode(row.Cells[1].Text);
      txtLName1.Text=Server.HtmlDecode(row.Cells[2].Text);
      txtAddr1.Text=Server.HtmlDecode(row.Cells[3].Text);
      txtPhone1.Text=Server.HtmlDecode(row.Cells[4].Text);

    }
  //If I hit another select button then this will load the sencond set of txtboxes
    if(string.IsNullOrEmpty(txtName2.Text) && string.IsNullOrEmpty(txtLName2.Text) &&
     string.IsNullOrEmpty(txtAddr2.Text) && string.IsNullOrEmpty(txtPhone2.Text))
    {
      txtName2.Text=Server.HtmlDecode(row.Cells[1].Text);
      txtLName2.Text=Server.HtmlDecode(row.Cells[2].Text);
      txtAddr2.Text=Server.HtmlDecode(row.Cells[3].Text);
      txtPhone2.Text=Server.HtmlDecode(row.Cells[4].Text);

    }
 //The thrid time will load the third button and so on until I fill each txtbox if I choose.
}

コマンド行の [選択] ボタンを押すたびに、複雑な if ステートメントをすべて配置する必要がなくなるように、これをコーディングするより良い方法はありますか? これを処理できる foreach ループのようなものはありますか?

4

2 に答える 2

0

最適化版はこちら

void GridView1_RowCommand(Object sender, GridViewCommandEventArgs e) {
    GridViewRow row = ((Control) sender).NamingContainer as GridViewRow;
    PopulateClients(txtName1, txtLName1, txtAddr1, txtPhone1, row);

    //If I hit another select button then this will load the sencond set of txtboxes
    PopulateClients(txtName2, txtLName2, txtAddr2, txtPhone2, row);
    //The thrid time will load the third button and so on until I fill each txtbox if I choose.
}

private void PopulateClients(TextBox t1, TextBox t2, TextBox t3, TextBox t4, GridViewRow r) {
    if (string.IsNullOrEmpty(t1.Text) && string.IsNullOrEmpty(t2.Text) && string.IsNullOrEmpty(t3.Text) && string.IsNullOrEmpty(t4.Text)) {
        t1.Text = Server.HtmlDecode(r.Cells[1].Text);
        t2.Text = Server.HtmlDecode(r.Cells[2].Text);
        t3.Text = Server.HtmlDecode(r.Cells[3].Text);
        t4.Text = Server.HtmlDecode(r.Cells[4].Text);    
    }
}​
于 2012-05-07T11:47:28.583 に答える
0

FindControl メソッドを見ることをお勧めします。

以下を使用できます。

TextBox txtName = FindControl(string.Format("txtName{0}", index) as TextBox;
if(txtName != null)
{
txtName.Text = row.Cells[1].Text;
}
于 2012-05-07T11:21:59.150 に答える