【问题标题】:automatically update label when entering content in textbox asp.net在文本框 asp.net 中输入内容时自动更新标签
【发布时间】:2017-02-07 08:32:46
【问题描述】:

我在 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();
    }
}

但这不起作用。同样在文本框中输入一个值后,如果我在框外单击,里面的文本就会消失。有没有其他方法可以做到这一点?还是我在这里做错了什么?

【问题讨论】:

  • @JeremyKern 他有一个脚本管理器和一个更新面板

标签: c# jquery sql asp.net


【解决方案1】:

我建议您添加一个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 = "";
   }
}

【讨论】:

  • 是的,我确定我正在从 DataTable 中获取内容,我已经验证了......好吧,我会用按钮尝试一下
  • @ManoUncharted - 告诉我你的进展情况
  • 我尝试了一个按钮,但还是一样。当我单击按钮时,文本框变为空..cleared
  • @ManoUncharted - 我已经更新了我的答案,请确保您没有在页面加载时清除标签
  • 哦好的..我应该为这个库添加什么?标题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多