我的C#Web应用程序中有一个GridView控件。在我的gridview中,我有一个名为Select,ID="btnSelect"
的ButtonField。基本上在我的GridView控件中,我有一个客户端名字,姓氏,地址和电话号码,对于相应的信息,我有文本框。当我点击/触发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.
}
有没有更好的方法将其编码到哪里如果每次按下Command命令行中的Select按钮,我都不必将那些复杂的if语句放在那里?是否有像foreach循环可以处理这个任何指导将非常感谢!
答案 0 :(得分:0)
我建议查看FindControl方法。
您可以使用以下内容:
TextBox txtName = FindControl(string.Format("txtName{0}", index) as TextBox;
if(txtName != null)
{
txtName.Text = row.Cells[1].Text;
}
答案 1 :(得分: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);
}
}