Asp.Net WebForm中SqlCommand传参控制按钮可见性报错排查
CheckLikedEvents Method Hey Mina, let's troubleshoot that null reference error you're hitting. That error almost always means one of your variables is null when you try to use it—let's break down the most likely issues and how to fix them:
1. You Can't Directly Find Controls Inside a DataList/WebControl
The biggest culprit here is probably your line dlEvents.FindControl("lnkbtnGoing"). If dlEvents is a DataList (or similar data-bound control like GridView), its child controls are nested inside DataListItem objects, not directly under the control itself. Calling FindControl on the parent dlEvents will return null, which causes the error when you try to set its Visible property.
Fix:
Loop through the DataList's items to find the button:
Button lnkbtnGoing = null; // Loop through each item in the DataList to locate the button foreach (DataListItem item in dlEvents.Items) { lnkbtnGoing = item.FindControl("lnkbtnGoing") as Button; if (lnkbtnGoing != null) { break; // Exit loop once we find the button } } // Only modify the button if we found it if (lnkbtnGoing != null) { lnkbtnGoing.Visible = !reader.HasRows; // Simplify: hide if reader has rows, show otherwise } else { lblErrormsg.Text = "Could not locate the 'lnkbtnGoing' button."; }
Double-check that the button's ID (lnkbtnGoing) matches exactly in your markup—WebForms is case-sensitive with control IDs!
2. Missing or Null EventId in Query String
If the URL doesn't include an EventId parameter, Request.QueryString["EventId"] will return null. Passing a null value to your SQL parameter might not break the query, but it's a good practice to validate this first to avoid unexpected behavior:
string eventId = Request.QueryString["EventId"]; if (string.IsNullOrEmpty(eventId)) { lblErrormsg.Text = "Event ID is missing from the request."; return; // Exit the method early if we don't have the required parameter }
3. Avoid Unnecessary Session Usage
You're storing the user ID in Session["id"], but you can directly use User.Identity.GetUserId() without the Session middleman. This reduces the chance of null values and makes your code cleaner:
string userId = User.Identity.GetUserId(); if (string.IsNullOrEmpty(userId)) { lblErrormsg.Text = "Failed to retrieve your user ID."; return; }
4. Properly Dispose Database Resources
Your current code doesn't close the SqlConnection or SqlDataReader, which can lead to connection leaks. Use using statements to automatically dispose these resources when you're done with them:
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myconn"].ConnectionString)) { using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT UserId, EventId FROM SavedEvents WHERE UserId = @id AND EventId = @eventId", conn)) { // Add parameters safely cmd.Parameters.AddWithValue("@id", userId); cmd.Parameters.AddWithValue("@eventId", eventId); conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { // Logic to find the button and set visibility goes here } } }
Full Modified Code
Putting it all together, here's the updated CheckLikedEvents method:
public void CheckLikedEvents() { if (User.Identity.IsAuthenticated) { string userId = User.Identity.GetUserId(); if (string.IsNullOrEmpty(userId)) { lblErrormsg.Text = "Failed to retrieve your user ID."; return; } string eventId = Request.QueryString["EventId"]; if (string.IsNullOrEmpty(eventId)) { lblErrormsg.Text = "Event ID is missing from the request."; return; } try { using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["myconn"].ConnectionString)) { using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT UserId, EventId FROM SavedEvents WHERE UserId = @id AND EventId = @eventId", conn)) { cmd.Parameters.AddWithValue("@id", userId); cmd.Parameters.AddWithValue("@eventId", eventId); conn.Open(); using (SqlDataReader reader = cmd.ExecuteReader()) { Button lnkbtnGoing = null; foreach (DataListItem item in dlEvents.Items) { lnkbtnGoing = item.FindControl("lnkbtnGoing") as Button; if (lnkbtnGoing != null) { break; } } if (lnkbtnGoing != null) { lnkbtnGoing.Visible = !reader.HasRows; } else { lblErrormsg.Text = "Could not locate the 'lnkbtnGoing' button."; } } } } } catch (Exception ex) { lblErrormsg.Text = DatabaseErrorMessage(ex.Message); } } }
内容的提问来源于stack exchange,提问作者Mina Bebawi

