Search code examples
c#asp.netstringlinkbutton

string text to many linkbuttons (asp.net c#)


I am retrieving data from table column where I have saved tags for the article, for example: "animals dogs cats" and showing this string text in linkbutton. If I click it, then page is redirected to "Tags.aspx?name=animals dogs cats".

Is it possible to redirect page to "Tags.aspx?name=cats" if I have clicked on "cats", or maybe to split the string and show each word in own linkbutton (without using something like listview)?

Thanks, Oak


Solution

  • If you don't want to use a web-databound control like Repeater you can create the LinkButtons dynamically. Remember to recreate them on postbacks with the same ID as before in Page_Load at the latest:

    protected void Page_Init(object sender, EventArgs e)
    {
        createTagButtons();
    }
    
    private void createTagButtons()
    { 
        var tblTags = new DataTable();
        using (var con = new SqlConnection(connectionString))
        using (var da = new SqlDataAdapter("SELECT TagID, TagName FROM dbo.Tags ORDER BY TagName", con))
        {
            da.Fill(tblTags);
        }
    
        foreach (DataRow row in tblTags.Rows)
        {
            int tagID =  row.Field<int>("TagID");
            string tagName = row.Field<string>("TagName");
            LinkButton tagButton = new LinkButton();
            tagButton.ID = "tagButton_" + tagID;
            tagButton.CommandArgument = tagName;
            tagButton.Click += TagLinkClicked;
            this.TagPanel.Controls.Add(tagButton);
        }
    }
    
    private void TagLinkClicked(Object sender, EventArgs e)
    {
        LinkButton tagLink = (LinkButton)sender;
        string url = string.Format("Tags.aspx?name={0}", tagLink.CommandArgument);
        Response.Redirect(url);
    }
    

    On the aspx you could use a Panel:

    <asp:Panel ID="TagPanel" runat="server"></asp:Panel>