none
GridView中Checked选取任何一行或多行,然后单击保存按钮,并不是取DataKeys的值,而是取得任意一列的值. RRS feed

  • 问题

  • 我的代码如下:

    protected void Button2_Click(object sender, EventArgs e)
        {

            string Mstr = "";
            CheckBox MychBox;
            foreach (GridViewRow G in GridView1.Rows)
            {
                MychBox = (CheckBox)G.FindControl("CheckBox1");
                if (MychBox.Checked)

    // CheckBox contact_Box = (CheckBox)GridView1.Rows[G.RowIndex].FindControl("CheckBox1");
            //contact_str = contact_Box.Text;
                    Mstr += Rowview.Cells[1].text + ",";
            }
            if (Mstr.Length <= 0)
                return;
            else
                Mstr = Mstr.Substring(0, Mstr.Length - 1);

            Response.Write(Mstr);
        }

     

    其中"Mstr += Rowview.Cells[1].text + ",";"这个地方怎么写才有效,我写的是错误的.

    2011年8月31日 8:46

答案

  • 请参考看看(注意粗体字地方)

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default8.aspx.cs" Inherits="Default8" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
     <title></title>
    </head>
    <body>
     <form id="form1" runat="server">
    
     <asp:SqlDataSource runat="server" ID="sds_Categories" ConnectionString="<%$ ConnectionStrings:NorthwindChineseConnectionString %>"
      SelectCommand="SELECT [CategoryID], [CategoryName], [Description] FROM [Categories]" />
     <br />
     <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="CategoryID"
      DataSourceID="sds_Categories">
      <Columns>
       <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" InsertVisible="False"
        ReadOnly="True" SortExpression="CategoryID" />
       <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" SortExpression="CategoryName" />
       <asp:BoundField DataField="Description" HeaderText="Description" SortExpression="Description" />
       <asp:TemplateField>
        <ItemTemplate>
         <asp:CheckBox ID="CheckBox1" runat="server" />
        </ItemTemplate>
       </asp:TemplateField>
      </Columns>
     </asp:GridView>
    
     <br />
     <asp:Button Text="送出" ID="Button2" runat="server" OnClick="Button2_Click" />
     </form>
    </body>
    </html>
    

     

     protected void Button2_Click(object sender, EventArgs e)
     {
      string Mstr = "";
      CheckBox MychBox;
      foreach (GridViewRow gvr in GridView1.Rows)
      {
       MychBox = (CheckBox)gvr.FindControl("CheckBox1");
    
       if (MychBox!=null && MychBox.Checked)
        Mstr += gvr.Cells[0].Text+ ",";
    
      }
    
      if (Mstr.Length <= 0)
       return;
      else
       Mstr = Mstr.Substring(0, Mstr.Length - 1);
    
      Response.Write(Mstr);
     }
    

     


    Shadowと愉快なコード達

    2011年8月31日 9:27