如何使用gridview中的按钮字段获取每行数据以在文本框中显示?

时间:2014-02-24 03:39:53

标签: c# asp.net sql gridview buttonfield

我想通过单击gridview中显示的Edit buttonfield在各自的文本框中显示我的gridview详细信息。我只能获取第一行(row [0])数据,默认情况下或通过点击其他行的全部数据。但是我需要通过单击每一行编辑按钮来获取每一行。这是我的设计代码。我使用的是VS 2013和SQL Server 2012。

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Admin.aspx.cs"     Inherits="RigoTest.Admin" %>
<!DOCTYPE html>
   <html xmlns="http://www.w3.org/1999/xhtml">
   <head runat="server">
   <title></title>
   <style type="text/css">
    .auto-style1 {
        width: 50%;
    }
  </style>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
    <asp:GridView ID="gvdetails" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" 
        GridLines="None" Width="800px" HorizontalAlign="Center" OnRowEditing="gvdetails_RowEditing" OnRowCommand="gvdetails_RowCommand">
        <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <Columns>
            <%--<asp:TemplateField HeaderText="ID" Visible="false">
                <EditItemTemplate>
                    <asp:TextBox ID="txtID" runat="server" Text='<%# Bind("ID") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblID" runat="server" Text='<%# Bind("ID") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Question">
                <EditItemTemplate>
                    <asp:TextBox ID="txtQue" runat="server" Text='<%# Bind("question") %>'></asp:TextBox>
                </EditItemTemplate>
                <ItemTemplate>
                    <asp:Label ID="lblQue" runat="server" Text='<%# Bind("question") %>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>


            --%>

            <asp:BoundField DataField="ID" HeaderText="ID" Visible="false" />
            <asp:BoundField DataField="question" HeaderText="Question" />

            <%--<asp:CommandField ShowEditButton="True" HeaderText="Edit2"  />--%>
            <asp:ButtonField HeaderText="Edit" CommandName="edit" Text="Edit" />
            <%--<asp:CommandField CausesValidation="False" HeaderText="Edit2" InsertVisible="False" ShowCancelButton="False" ShowEditButton="True" UpdateText="" />--%>
        </Columns>
        <EditRowStyle BackColor="#999999" />
        <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
        <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" HorizontalAlign="Left" />
        <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
        <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
        <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
        <SortedAscendingCellStyle BackColor="#E9E7E2" />
        <SortedAscendingHeaderStyle BackColor="#506C8C" />
        <SortedDescendingCellStyle BackColor="#FFFDF8" />
        <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
    </asp:GridView>
</center>
</div>



    <div style="height: 300px; margin-top: 250px">
        <center>
        <table width="40%" class="auto-style1">
            <tr>
                <td>
                    Add/Edit Question</td>
                <td>
                    &nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>
                    &nbsp;</td>
                <td>
                    &nbsp;</td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="Label5" runat="server" Text="Question :"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtquestion" runat="server" Width="295px"></asp:TextBox>
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="Label3" runat="server" Text="Option :"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtoption" runat="server" Width="295px"></asp:TextBox>
                </td>
                <td>
                    <asp:Button ID="btnadd" runat="server" Text="Add" Width="50px" OnClick="btnadd_Click" />
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:ListBox ID="ListBox1" runat="server" Width="300px"></asp:ListBox>
                </td>
                <td>
                    <asp:Button ID="btndelete" runat="server" Text="Delete" Width="50px" OnClick="btndelete_Click" />
                    <br />
                    <br />
                    <asp:Button ID="btnselect" runat="server" Text="Select" Width="50px" OnClick="btnselect_Click" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="Label4" runat="server" Text="Correct Option :"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtcorrectoption" runat="server" Width="295px"></asp:TextBox>
                </td>
                <td>&nbsp;</td>
            </tr>
            <tr>
                <td>
                    <br />
                    <asp:Button ID="btnsave" runat="server" Text="Save" Width="100px" />
                </td>
                <td>&nbsp;</td>
                <td>&nbsp;</td>
            </tr>
        </table>
        </center>
    </div>
</form>
    </body>

这是我的ASP.NET代码

public partial class Admin : System.Web.UI.Page
{
    SqlConnection con = new SqlConnection("server = yamma; uid = sa; pwd = /*-; database = rigo");
    SqlCommand cmd;
    SqlDataAdapter da = new SqlDataAdapter();
    DataTable dt = new DataTable();
    public static DataTable dtDefault = new DataTable(); 
    public Int64 n;
    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            showdata();
            //string EditID = Request.QueryString["EditId"];
        }

    }

    public void showdata()
    {
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        cmd = new SqlCommand("RigoSelect", con);
        cmd.CommandType = CommandType.StoredProcedure;
        da.SelectCommand = cmd;
        da.Fill(dt);
        da.Fill(dtDefault);
        gvdetails.DataSource = dt;
        gvdetails.DataBind();

    }



    protected void btnadd_Click(object sender, EventArgs e)
    {
        ListBox1.Items.Add(txtoption.Text);         //to select data from textbox to listbox
    }

    protected void btndelete_Click(object sender, EventArgs e)
    {
        string remove = ListBox1.SelectedItem.Text;
        ListBox1.Items.Remove(remove);

        ////clear all items in listbox
        //listBox1.Items.Clear();
    }

    protected void btnselect_Click(object sender, EventArgs e)
    {
        txtcorrectoption.Text = ListBox1.SelectedItem.Text;
    }

    protected void gvdetails_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //private Int64 n;
        //for(int i=0;i<=n;i++)
        //{
        int id = int.Parse(gvdetails.Rows[0].Cells[0].Text);

        DataRow[] dr = null;
        dr = dtDefault.Select("ID = '" + id + "'");
        txtquestion.Text = dr[0]["question"].ToString();
        txtoption.Text = dr[0]["options"].ToString();
        //}
        showdata();


    }

    protected void gvdetails_RowEditing(object sender, GridViewEditEventArgs e)
    {
        // when boundfied is exist in gridview then id can get....thisway
        //int id = int.Parse(gvdetails.Rows[e.NewEditIndex].Cells[0].Text);

        ////Label lbl = (Label)gvdetails.Rows[e.NewEditIndex].Cells[0].FindControl("lblID");
        ////string id = lbl.Text.Trim();
        ////int EID = int.Parse(id);
        //// Response.Redirect("Admin.aspx?EditId=" + id + "");

        //DataRow[] dr = null;
        //dr = dtDefault.Select("ID = '" + id + "'");
        //txtquestion.Text = dr[0]["question"].ToString();
        //txtoption.Text = dr[0]["options"].ToString();

        //showdata();
    }


     }
 }

  My problem occurs here 

   protected void gvdetails_RowCommand(object sender, GridViewCommandEventArgs e)
     {
        //private Int64 n;
        //for(int i=0;i<=n;i++)
        //{
        int id = int.Parse(gvdetails.Rows[0].Cells[0].Text);

        DataRow[] dr = null;
        dr = dtDefault.Select("ID = '" + id + "'");
        txtquestion.Text = dr[0]["question"].ToString();
        txtoption.Text = dr[0]["options"].ToString();
        //}
        showdata();


    }

以下是我遇到的主要问题:

  protected void gvdetails_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        //private Int64 n;
        //for(int i=0;i<=n;i++)
        //{
        int id = int.Parse(gvdetails.Rows[0].Cells[0].Text);

        DataRow[] dr = null;
        dr = dtDefault.Select("ID = '" + id + "'");
        txtquestion.Text = dr[0]["question"].ToString();
        txtoption.Text = dr[0]["options"].ToString();
        //}
        showdata();


    }

当我点击任何只显示第一行数据的行时。我想通过每次单击网格行的相应文本框来获取每行数据。

我尝试过使用commandfield但是当尝试使用添加按钮在列表框中添加选项文本框(txtoption)的数据时,它会自动在gridview中显示更新,取消选项。

2 个答案:

答案 0 :(得分:1)

gvdetails_RowCommand事件中,您始终可以访问GridView中的第一行。

int id = int.Parse(gvdetails.Rows[0].Cells[0].Text);

查看是否有效(引用当前选定的行):

int id = int.Parse(gvdetails.SelectedRow.Cells[0].Text);

答案 1 :(得分:0)

以下是供您参考的示例代码。希望这可以帮助。

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName =="edit")
        {
            int i = Convert.ToInt32(e.CommandArgument);
            YourTextBox1.Text = GridView1.Rows[i].Cells[0].Text;
            YourTextBox2.Text = GridView1.Rows[i].Cells[1].Text;

        }
    }
相关问题