簡體   English   中英

asp.net datagrid視圖在文本框中的行選擇

[英]asp.net datagrid view row selection into textbox

當用戶單擊網格視圖中的“編輯”按鈕時,我需要將行選擇放入文本框的幫助,我有此事件,並將向您顯示我嘗試過的代碼。 我在Visual Studio 2013和SQL Server 2012上運行。

txtname.Text = gridview.Rows[gridview.SelectedIndex].Cells[1].Text;

txtname.Text = gridview.Rows[gridview.SelectedRow].Cells[1].Text;

[屏幕] http://imgur.com/WCsvnLB,cLdMeQN

而不是gridview.SelectedIndex您應該有一個事件arg並獲取它的索引。 文檔

protected void TaskGridView_RowEditing(object sender, GridViewEditEventArgs e)
  {
    //Set the edit index.
    TaskGridView.EditIndex = e.NewEditIndex;
    //Bind data to the GridView control.
    BindData();
  }

因此,您將是:

protected void gridView_RowEditing(object sender, GridViewEditEventArgs e)
{
   txtname.Text = gridview.Rows[e.NewEditIndex].Cells[1].Text;
}

首先使用下面的代碼創建一個Gridview

 <asp:GridView ID="GV" runat="server" AutoGenerateColumns="false"  OnRowEditing="GV_RowEditing" DataKeyNames="id">
        <Columns>
            <asp:TemplateField HeaderText="Username">
                <ItemTemplate>
                    <asp:Label ID="Label1" runat="server" Text='<%#Eval("Column1")%>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Password">
                <ItemTemplate>
                    <asp:Label ID="Label2" runat="server" Text='<%#Eval("Column2")%>'></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
            <asp:TemplateField HeaderText="Action">
                <ItemTemplate>
                    <asp:LinkButton ID="LinkButton1" runat="server" CommandName="edit" OnClick="LinkButton1_Click" >Edit</asp:LinkButton>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>

然后生成gridview的行編輯事件,並在其中編寫此代碼

 string id = GV.DataKeys[e.NewEditIndex].Value.ToString();
    string select = "select * from tblLogin where id ='"+Convert.ToInt16(id)+"'";
    ds = gs.select(select);
    if (ds.Tables[0].Rows.Count > 0)
    {
       lblName.Text= ds.Tables[0].Rows[0]["Column1"].ToString();
        lblPass.Text=ds.Tables[0].Rows[0]["Column2"].ToString();
    }

希望這會有所幫助

因此,我結合使用了兩個答案,並得出了一個效果很好的答案:

int id = Convert.ToInt32(gridview.DataKeys[e.NewEditIndex].Value);
    txtid.Text = id.ToString();
    txtname.Text = gridview.Rows[id].Cells[3].Text;
    txtadd.Text = gridview.Rows[id].Cells[4].Text;
    txtcountry.Text = gridview.Rows[id].Cells[5].Text;
    txtcity.Text = gridview.Rows[id].Cells[6].Text;
    txtpin.Text = gridview.Rows[id].Cells[7].Text;

讓我知道您的想法,如果編碼不好,也請告訴我。

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM