簡體   English   中英

在文本框asp.net中輸入內容時自動更新標簽

[英]automatically update label when entering content in textbox asp.net

我在ASP.NET中有一個文本框和一個標簽,我想使用數據庫中使用文本框中輸入的內容獲取的值自動更新標簽。 當在文本框中更改文本時,應動態完成此操作;如果在數據庫中找到匹配項,則應在標簽字段中顯示相應的值(不刷新頁面)。 在這種情況下,我將在文本框中輸入員工ID,員工名稱應顯示在標簽中。 我正在使用以下代碼,

<asp:ScriptManager ID="script_manager" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="update_name" runat="server">
    <ContentTemplate>
        <asp:TextBox ID="text_empID" TextMode="Number" MaxLength="6" AutoPostBack="true" OnTextChanged="text_empID_TextChanged" runat="server"></asp:TextBox>
        <asp:Label ID="label_empName" runat="server"></asp:Label>
    </ContentTemplate>
</asp:UpdatePanel>

后面的代碼如下,

protected void text_empID_TextChanged(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);
    con.Open();
    SqlCommand cmd = new SqlCommand("select EmployeeName from EmployeeTable where EmployeeID=@id", con);
    cmd.Parameters.AddWithValue("@id", text_empID.Text);
    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);
    if (dt.Rows.Count > 0)
    {
        label_empName.Text = dt.Rows[0]["EmployeeName"].ToString();
    }
}

但這是行不通的。 同樣在文本框中輸入值后,如果我在框外單擊,里面的文本也會消失。 還有其他方法嗎? 還是我在這里做錯了什么?

我建議您添加一個button因為text_changed事件僅在文本框blurs (失去焦點)時才觸發。

這是一個非常奇怪的行為,大多數用戶都不習慣並且不會期望它。

<ContentTemplate>
   <asp:TextBox ID="text_empID" TextMode="Number" MaxLength="6" runat="server></asp:TextBox>
   <asp:button id="btnSearch" runat="server" OnClick="text_empID_TextChanged" />
   <asp:Label ID="label_empName" runat="server"></asp:Label>
</ContentTemplate>

無論如何,您是否添加了斷點? 事件會觸發嗎? 您是否在DataTable中獲取了任何數據?

編輯

在您發表最后評論之后,我確信您正在清除頁面加載時的標簽內容。

請確保僅在以下情況下執行此操作:

protected void Page_Load(object sender, EventArgs e)
{
   if(!Page.IsPostBack)
   {
      label_empName.Text = "";
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM