多种方式读取GridView某行的值

//方法一
//读取单元格(不支持隐藏列)
//GridView1.SelectedRow.Cells[int index] //index从1开始
txtID.Text = GridView1.SelectedRow.Cells[1].Text.Trim();
txtName.Text = GridView1.SelectedRow.Cells[2].Text.Trim();
txtSex.Text = GridView1.SelectedRow.Cells[3].Text.Trim();

//方法二
//读取每一行的数据键值(支持隐藏列)
//DataKeyArray GridView1.DataKeys[int index][int index]
//index均从0开始
txtID.Text = GridView1.DataKeys[GridView1.SelectedIndex][0].ToString();
txtName.Text = GridView1.DataKeys[GridView1.SelectedIndex][1].ToString();
txtSex.Text = GridView1.DataKeys[GridView1.SelectedIndex][2].ToString();
txtAge.Text = GridView1.DataKeys[GridView1.SelectedIndex][3].ToString();

//方法三
//读取选中行的数据键值(支持隐藏列)
//DataKey GridView1.SelectedDataKey[int index]
//index从0开始
txtID.Text = GridView1.SelectedDataKey[0].ToString();
txtName.Text = GridView1.SelectedDataKey[1].ToString();
txtSex.Text = GridView1.SelectedDataKey[2].ToString();
txtAge.Text = GridView1.SelectedDataKey[3].ToString();

//方法四

//查找服务器控件ID(支持隐藏列)
txtID.Text = ((Label)GridView1.SelectedRow.Cells[1].FindControl("lblID")).Text.Trim();
txtName.Text = ((Label)GridView1.SelectedRow.Cells[2].FindControl("lblName")).Text.Trim();
txtSex.Text = ((Label)GridView1.SelectedRow.Cells[3].FindControl("lblSex")).Text.Trim();
txtAge.Text = ((Label)GridView1.SelectedRow.Cells[4].FindControl("lblAge")).Text.Trim();

//方法五
//通过SQL查询返回(因为GridView只需绑定id列,所以不存在隐藏列问题。)
txtID.Text = ((Label)GridView1.SelectedRow.FindControl("lblID")).Text.Trim();
YouNamespace.Model.User model = new YouNamespace.Model.User();
model = new YouNamespace.BLL.User().GetModel(int.Parse(txtID.Text.Trim()));
txtName.Text = model.name;
txtSex.Text = model.sex;
txtAge.Text = model.age.ToString();

posted @ 2015-04-02 15:12  xnfzy  阅读(211)  评论(0编辑  收藏  举报