2014-07-07 21 views
0

有两个页面命名为:People.aspx和Profile.aspx。使用ASP.net中的按钮字段获取Gridview中选定行的数据字段

People.aspx - >包含所有用户的名称

Profile.aspx - >包含每个用户

的信息,在第一页中,People.aspx,我有一个GridView命名peopleGridview当我加载页面名称People.aspx,在Page_Load事件中,我调用一个方法对数据库执行sql查询,并获取我需要放入Gridview中的所有字段。

的SQL查询是这样的:

public DataSet PeopleList() 
    { 
     GetConnection(); 
     SqlCommand command = new SqlCommand("SELECT Members.ID, Members.Full_Name, Members.Position, Members.Status, Profile.Address" + 
              " FROM Members" + 
              " INNER JOIN Profile" + 
              " ON Members.ID = Profile.ID"+ 
              " ORDER BY Members.Priority, Members.Membership_Date, Members.Full_Name", con); 
     SqlDataAdapter da = new SqlDataAdapter(command);//da: DataAdapter 
     DataSet ds = new DataSet();//ds: Dataset 
     da.Fill(ds); 
     con.Close(); 
     return ds; 
    } 

在GridView的我只需要显示的字段FULL_NAME位置状态地址,我不希望显示值域ID(因为普通用户不需要知道其他用户的ID)。

我有一个按钮场在我的GridView的每一行,我想只要我点击所选行的按钮域,读取域选定行ID(目前未在GridView的显示)并将其作为用户标识的参数放入Response.Redirect("Profile.aspx?UserID=" + userid.Text.ToString());,以便将其发送到Profile.aspx这是另一个包含有关该用户信息的页面。

我该如何做这样的工作?另外,我如何获得Profile.aspx侧面的UserID的值

我在GridView中使用链接字段进行了这项工作,但是我无法在GridView中使用按钮字段做这样的工作。

回答

3

要获取网格视图中的特定列,首先将false值设置为自动生成列AutoGenerateColumns="False",然后在Gridview列中绑定您的必需字段。

HTML的GridView:

<asp:GridView ID="GridView1" CssClass="gridview" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand" > 
    <Columns> 
     <asp:BoundField DataField="Full_Name" HeaderText="Full Name" SortExpression="Full Name" /> 
     <asp:BoundField DataField="Position" HeaderText="Postion" SortExpression="Position" /> 
     <asp:BoundField DataField="Address" HeaderText="Address" SortExpression="Address" /> 
     <asp:TemplateField HeaderText="View Profile"> 
      <ItemTemplate> 
       <div style="text-align: center;"> 
        <asp:ImageButton ID="ImgBtnViewInq" runat="server" ImageUrl="~/images/Viewmail.png" 
         CommandName="ViewProfile" CommandArgument='<%# Eval("UserID") %>' ToolTip="View Profile" /> 
       </div> 
      </ItemTemplate> 
     </asp:TemplateField> 
    </Columns> 
</asp:GridView> 

C#代码背后:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) 
{ 
    if (e.CommandName == "ViewProfile") 
    { 
     // id with get the Userid parameter that we set inside the button CommandArgument='<%# Eval("UserID") %>' 
     int id = Convert.ToInt32(e.CommandArgument); 

     // Send this value of id to your querystring to redirect to another page 
     Response.Redirect("Profile.aspx?UserId=" + id); 
    } 
} 
+0

还有一个问题。我有点困惑。我的sql查询的'ID'字段在哪里?你在哪里得到了代码中所选行的'ID'字段的值? – Pedram

+0

仔细阅读我的代码中的评论。它在你的网格视图按钮中显示“CommandArgument ='<%#Eval(”UserID“)%>'”。 –

+0

CommandArgument应该是'ID',而不是'UserId',我认为。因为在你的代码中,我有一个错误,并在将参数值更改为'ID'后,我不再有错误。但还有一个问题。当我点击按钮时,新页面不会加载,并且出现错误“无效的回发或回调参数。”这个是来做什么的? – Pedram

相关问题