Reputation: 381
I am trying to create a "Select User" page, which will dynamically pull user data from a database, and then generate a link for each user found in the database to select from. When the link is clicked, it will call a C# function to create a cookie and redirect the user.
The code correctly pulls the users from the database and generates the links, however the links do not function. Here is the C# code which generates the links:
String sqlStatement = "SELECT * FROM TUsers";
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
SqlCommand comm = new SqlCommand(sqlStatement, conn);
conn.Open();
SqlDataReader Reader = comm.ExecuteReader();
while (Reader.Read())
{
container.InnerHtml += "<a runat='server' href='#' onServerClick='UserButton_Click' > <div class='users'> <p>" + Reader["FirstName"] + " " + Reader["LastName"] + "</p> </div> </a>";
}
Reader.Close();
conn.Close();
Here is the HTML Source code on the generated page:
<div id="container"><a runat='server' href='#' onServerClick='UserButton_Click' > <div class='users'> <p>User 1</p> </div> </a>
The backend C# code for when the link is clicked is irrelevant for this question. Using breakpoints, the function that is supposed to be called is never called to begin with.
I have tried using HTML anchors with onServerClick, which so far is not actually running the proper function, as well as attempting to use <asp:LinkButton>
items, however from what I could tell, they were not parsing correctly due to being generated via container.InnerHtml.
Upvotes: 2
Views: 216
Reputation: 73741
You could use a ListView control to get what you want:
<asp:ListView ID="lvUsers" runat="server">
<ItemTemplate>
<div>
<asp:LinkButton ID="lnkUser" runat="server" OnClick="lnkUser_Click" Text='<%# Eval("FirstName") + " " + Eval("LastName") %>' />
</div>
</ItemTemplate>
</asp:ListView>
The data source of the ListView could be set like this:
using (SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (SqlCommand comm = new SqlCommand("SELECT * FROM TUsers", conn))
{
SqlDataAdapter dataAdapter = new SqlDataAdapter(comm);
DataSet ds = new DataSet();
dataAdapter.Fill(ds, "Users");
lvUsers.DataSource = ds.Tables[0];
lvUsers.DataBind();
}
And the event handler would be similar to what you already have:
protected void lnkUser_Click(object sender, EventArgs e)
{
// Process user data and redirect
}
Upvotes: 4