将Gridview值分配给文本框

本文关键字:文本 分配 Gridview | 更新日期: 2023-09-27 17:50:49

我要问一个关于c#,Asp.net…我创建了3个文本框为empid,名称和地址

点击"编辑按钮",在文本框中手动输入empid。我想分配另外两个值name &地址到他们的文本框。然后我使用更新按钮更新

有人能教我写代码吗?

//Asp.net 
 <form id="form1" runat="server">
<div>
    <asp:Label ID="Label1" runat="server" Text="Empid" Width="50px"></asp:Label>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <br />
    <asp:Label ID="Label2" runat="server" Text="Name" Width="50px"></asp:Label>
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <br />
    <asp:Label ID="Label3" runat="server" Text="Address" Width="50px"></asp:Label>
    <asp:TextBox ID="TextBox3" runat="server"></asp:TextBox>
    <br />
    <br />
    <br />
    <br />
    <asp:GridView ID="GridView1" runat="server">
    </asp:GridView>
    <br />
</div>
    <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="update " />
    <asp:Button ID="Button2" runat="server" Text="Edit" Width="61px" />
</form>

 //Cs for update button 

    SqlConnection conn = new SqlConnection("Data Source=s''SQLEXPRESS;Initial catalog = sample;Integrated security=True");
    SqlCommand cmd = new SqlCommand("UPDATE empdetails SET Name='" + TextBox2.Text + "',Address='" + TextBox3.Text + "' WHERE Empid ='" + TextBox1.Text + "'", conn);
    conn.Open();
    cmd.ExecuteNonQuery();
    cmd.CommandText = "SELECT * FROM Empdetails";
    GridView.DataSource = cmd.ExecuteReader();
    GridView.DataBind();
    TextBox1.Text = "";
    TextBox2.Text = "";
    TextBox3.Text = "";
    conn.Close();

我这样编码,如果我编辑按钮,输入Empid,我想要其他值名称&地址将分配给文本框

将Gridview值分配给文本框

步骤:

  1. 在GridView中获取Employee详细信息。

    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        GetEmpDetails()
    End Sub
    Private Sub GetEmpDetails()
    SqlConnection conn = new SqlConnection("Data Source=s''SQLEXPRESS;Initial catalog = sample;Integrated security=True");
    conn.Open();
    cmd.CommandText = "SELECT * FROM Empdetails";
    GridView.DataSource = cmd.ExecuteReader();
    GridView.DataBind();
    End Sub
    
  2. 将此属性AutoGenerateSelectButton="True"添加到设计页面的gridview中

    <asp:GridView ID="GridView1" runat="server" 
              AutoGenerateColumns="False"
              AutoGenerateSelectButton="True" 
              CellPadding="4" >
    </asp:GridView>
    
  3. 在网格的SelectedIndexChanged上获取RowIndex,以便我们将获得所选行的行值。

    Protected Sub GridView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles GridView1.SelectedIndexChanged
        LoadValues(GridView1.SelectedRow.RowIndex)
    End Sub
    
  4. 然后将网格值加载到相应的文本框中。

  5. 和改变你想要的值,但不改变ID(强烈建议)

  6. 然后点击更新按钮。在那里调用Update Query。
  7. 再次加载网格值并绑定它。这样你就可以立即看到变化。

编码. .快乐! !:)