locked
Turning usernames inside a content to show as links in Datalist in ASP.NET not working RRS feed

  • Question

  • User-2074858223 posted

    Hi i have this example below that shows usernames that are found in a user content to be displayed as a link, but the example below was coded using static content instead of database content, so am trying to use data from database to create the example but is not working.

    See the original example code:

    <asp:DataList ID="Getcontent" runat="server" OnItemDataBound="Getcontent_ItemDataBound">
        <ItemTemplate>
            <table>
                <tr>
                    <td>
                        <b>ID:</b>
                        <asp:Label ID="lblId" Text='<%# Eval("Id") %>' runat="server" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Name:</b>
                        <asp:Label ID="lblUserName" Text='<%# Eval("UserName")%>' runat="server" />
                    </td>
                </tr>
                <tr>
                    <td>
                        <b>Description:</b><br />
                        <asp:Label ID="lblDescription" Text='<%# Eval("Sentence")%>' runat="server" />
                    </td>
                </tr>
            </table>
        </ItemTemplate>
    </asp:DataList>
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            PopulateBooks();
        }
    }
     
    private void PopulateBooks()
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[] { new DataColumn("Id"), new DataColumn("UserName"), new DataColumn("Sentence") });
        dt.Rows.Add(1, "mic", "hello andy!");
        dt.Rows.Add(2, "mic", "he mic, i am antonio");
        dt.Rows.Add(3, "mic", "Welcome andy,<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;andy now you can ask question.");
        dt.Rows.Add(3, "mic", "convert word in a sentence to hyperlink");
        GetContent.DataSource = dt;
        GetContent.DataBind();
    }
     
    private DataTable GetUserNameFromAccount()
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[] { new DataColumn("Id"), new DataColumn("Name") });
        dt.Rows.Add(1, "mic");
        dt.Rows.Add(2, "andy");
        dt.Rows.Add(3, "brown");
        dt.Rows.Add(3, "antonio");
        return dt;
    }
     
    protected void GetContent_ItemDataBound(object sender, DataListItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            DataTable dtName = GetUserNameFromAccount();
            for (int i = 0; i < dtName.Rows.Count; i++)
            {
                if ((e.Item.FindControl("lblDescription") as Label).Text.Contains(dtName.Rows[i]["Name"].ToString()))
                {
                    (e.Item.FindControl("lblDescription") as Label).Text = (e.Item.FindControl("lblDescription") as Label).Text.Replace(dtName.Rows[i]["Name"].ToString(), "<a href=#>" + dtName.Rows[i]["Name"] + "</a>");
                }
            }
        }
    }

    This is what i tried, i tried fetching the content from database and it didn't work, i don't know if am missing something?

    protected void Page_Load(object sender, EventArgs e)
        {
             if (!IsPostBack)
            {
                this.Getfollowers();
            }
        }
     
        private void Getfollowers()
        {
            // username = this.Page.User.Identity.Name;
            //string userId = Session["UserId"].ToString();
            string text = "";
            string getADPOST = "GetUserPOSTS";
            using (SqlConnection con = new SqlConnection(constring))
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand(getADPOST, con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    {
                        cmd.Parameters.AddWithValue("@UserName", Session["userName"]);
                        // cmd.Parameters.AddWithValue("@FriendUserName", username);
                        //  cmd.Parameters.AddWithValue("@ID", getADPOST);
                        DataTable dt = new DataTable();
                        dt.Columns.AddRange(new DataColumn[] { new DataColumn("Id"), new DataColumn("UserName"), new DataColumn("ContentPost") });
                       
                        SqlDataAdapter sda = new SqlDataAdapter(cmd);
                        sda.Fill(dt);
     
                        GetContent.DataSource = dt;
                        GetContent.DataBind();
                    }
                }
            }
         
     
         if (!Page.IsPostBack)
            {
                 
     
                if (this.Page.User.Identity.IsAuthenticated)
                {
                   // this.GetUserDetail();
                    
                }
            }
        }
        //user account
    private DataTable GetUserNameFromAccount()
        {
            string username5 = this.Page.User.Identity.Name;
            string str = ConfigurationManager.ConnectionStrings["DB"].ConnectionString;
            string getADPOST = "GetUSERPRO";
            using (SqlConnection con = new SqlConnection(str))
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand(getADPOST, con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataTable ds = new DataTable();
     
                    ds.Columns.AddRange(new DataColumn[] { new DataColumn("Id"), new DataColumn("UserName") });
                    return ds;
     
     
                }
            }
           
        }
     
        protected void GetContent_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DataTable dtName = GetUserNameFromAccount();
                for (int i = 0; i < dtName.Rows.Count; i++)
                {
                    if ((e.Item.FindControl("lblDescription") as Label).Text.Contains(dtName.Rows[i]["UserName"].ToString()))
                    {
                        (e.Item.FindControl("lblDescription") as Label).Text = (e.Item.FindControl("lblDescription") as Label).Text.Replace(dtName.Rows[i]["UserName"].ToString(), "<a href=#>" + dtName.Rows[i]["UserName"] + "</a>");
                    }
                }
            }
        }
    }

    Thursday, January 25, 2018 7:51 AM

Answers

  • User475983607 posted

    Try to think about the issue logically.  If your test works as expected but live data does not work, then the test data is not representative of the actual data.  This can be due to a faulty test or faulty data  We cannot see the database.

    Is there any reason why you don't use the Visual Studio debugger to step through your code and view the local variables?  IMHO, this would be much faster than posting on a forum. 

    Can you tell us if the for loop is entered?  Is the If condition entered?  Is so, what is the value of e.Item.FindControl("lblDescription") and dtName.Rows[i]["UserName"].ToString()?

    Why are you using dtName.Rows[i]["UserName"].ToString() as opposed to e.Item.FindControl("UserName")?   The syntax dtName.Rows[i]["UserName"] returns a column, right???  I'm guessing that's where the problem is located.  A problem the debugger can easily show. 

    The following link show how to use the Visual Studio debugger.

    https://msdn.microsoft.com/en-us/library/y740d9d3.aspx

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 26, 2018 2:00 PM

All replies

  • User-1838255255 posted

    Hi micah2012,

    According to your description and code, you say not working, if you meet some error information or which line code caused website break, please tell us the detail of the exception. 

     private void Getfollowers()
        {
            // username = this.Page.User.Identity.Name;
            //string userId = Session["UserId"].ToString();
            string text = "";
            string getADPOST = "GetUserPOSTS";
            using (SqlConnection con = new SqlConnection(constring))
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand(getADPOST, con))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    {
                        cmd.Parameters.AddWithValue("@UserName", Session["userName"]);
                        // cmd.Parameters.AddWithValue("@FriendUserName", username);
                        //  cmd.Parameters.AddWithValue("@ID", getADPOST);
                        DataTable dt = new DataTable();
                        dt.Columns.AddRange(new DataColumn[] { new DataColumn("Id"), new DataColumn("UserName"), new DataColumn("ContentPost") });
                       
                        SqlDataAdapter sda = new SqlDataAdapter(cmd);
                        sda.Fill(dt);
     
                        GetContent.DataSource = dt;
                        GetContent.DataBind();
                    }
                }
            }
         
     
         if (!Page.IsPostBack)
            {
                 
     
                if (this.Page.User.Identity.IsAuthenticated)
                {
                   // this.GetUserDetail();
                    
                }
            }
        }

    I checked your code, i notice that in the Getfollowers method, you use the constring variable as connection string, but i notice that you don't get it, please add the following code to get the connection string. 

     string constring = ConfigurationManager.ConnectionStrings["connectstring name in web.config"].ConnectionString;

    For more details. please check the following sample:

    https://www.aspsnippets.com/Articles/Populate-ASPNet-DataList-by-binding-DataSet-Client-Side-using-jQuery-AJAX.aspx 

    Best Regards,

    Eric Du 

    Friday, January 26, 2018 7:56 AM
  • User-2074858223 posted

    No am not saying that i cant populate the Datalist, the contents are showing on datalist, but the issue is the code above supposed to turn usernames found in the content to a link, so the error is the content is showing but the usernames found in the content are not links

        protected void GetContent_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                DataTable dtName = GetUserNameFromAccount();
                for (int i = 0; i < dtName.Rows.Count; i++)
                {
                    if ((e.Item.FindControl("lblDescription") as Label).Text.Contains(dtName.Rows[i]["UserName"].ToString()))
                    {
                        (e.Item.FindControl("lblDescription") as Label).Text = (e.Item.FindControl("lblDescription") as Label).Text.Replace(dtName.Rows[i]["UserName"].ToString(), "<a href=#>" + dtName.Rows[i]["UserName"] + "</a>");
                    }
                }

    Friday, January 26, 2018 9:44 AM
  • User475983607 posted

    Try to think about the issue logically.  If your test works as expected but live data does not work, then the test data is not representative of the actual data.  This can be due to a faulty test or faulty data  We cannot see the database.

    Is there any reason why you don't use the Visual Studio debugger to step through your code and view the local variables?  IMHO, this would be much faster than posting on a forum. 

    Can you tell us if the for loop is entered?  Is the If condition entered?  Is so, what is the value of e.Item.FindControl("lblDescription") and dtName.Rows[i]["UserName"].ToString()?

    Why are you using dtName.Rows[i]["UserName"].ToString() as opposed to e.Item.FindControl("UserName")?   The syntax dtName.Rows[i]["UserName"] returns a column, right???  I'm guessing that's where the problem is located.  A problem the debugger can easily show. 

    The following link show how to use the Visual Studio debugger.

    https://msdn.microsoft.com/en-us/library/y740d9d3.aspx

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, January 26, 2018 2:00 PM