Search code examples
c#asp.nettextboxlinkbutton

Make text appear in a textbox when clicking on button


I have some text which I want to appear in a textbox which I click on the linkbutton "Edit" As you can see I have CommandNames and CommandArguments on those linkbuttons so I need a solution which can be written in the codebehind (.cs) as I got an if (e.CommandName == "Edit")

I haven't tried anything, as I can't find anything about it, neither in my head.

Designer Code:

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1" OnItemCommand="Repeater1_ItemCommand">
    <asp:ItemTemplate>
        <tr>
            <td>
                <asp:TextBox ID="TextBox_Text" runat="server" Text='<%# Eval("Text") %>'>
            </td>
            <td>
                <asp:LinkButton ID="LinkButton_Save" runat="server" CommandName="Save" CommandArgument='<%# Eval("Id") %>'> Save </asp:LinkButton>
            </td>
            <td>
                <asp:LinkButton ID="LinkButton_Edit" runat="server" CommandName="Edit" CommandArgument='<%# Eval("Id") %>'> Edit </asp:LinkButton>
            </td>
            <td>
                <asp:LinkButton ID="LinkButton_Delete" runat="server" CommandName="Delete" CommandArgument='<%# Eval("Id") %>'> Delete </asp:LinkButton>
            </td>
        </tr>
    </asp:ItemTemplate>
</asp:Repeater>

<asp:SqlDataSource runat="server" ID="SqlDataSource_Forside" ConnectionString='<%$ ConnectionStrings:ConnectionString %>' SelectCommand="SELECT * FROM [Table1]"> <asp:SqlDataSource>


Code behind:


if (e.CommandName == "Edit")
    {
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString =
            ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandText = "Select * FROM Table1 WHERE Id = @Id";


        cmd.Parameters.Add("@Id", SqlDbType.Int).Value = e.CommandArgument.ToString();

        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader();

        if (reader.Read())
        {
            TextBox_Edit.Text = reader["Text"].ToString(); // i dont have the textbox yet..
        }
        conn.Close();

        Repeater1.DataBind();

    }

Solution

  • This is what you have to do:

    if (e.CommandName == "Edit")
    {
        SqlConnection conn = new SqlConnection();
        conn.ConnectionString =
            ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
    
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandText = "Select * FROM Table1 WHERE Id = @Id";
    
    
        cmd.Parameters.Add("@Id", SqlDbType.Int).Value = e.CommandArgument.ToString();
    
        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader();
    
    
        TextBox_Text.Text=reader["Text"].ToString();;
    
        conn.Close();
    
        Repeater1.DataBind();
    
    }