AJAX TextChanged 事件練習 抓DB資料版
============ 下面是 說明的部份 ============================
當TextBox1輸入值後,當focus離開TextBox1後,會去呼叫後台的C# CODE
C# CODE就看需要什麼資料再自己加就好,抓DB資料版
多筆資料要注意接資料的控制項,本版是Label
============ 下面是 HTML 的部份 ==========================
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" >
</asp:ScriptManager>
<table class="style1">
<tr>
<td class="style2">
key in :
</td>
<td>
<asp:TextBox ID="TextBox1" runat="server"
ontextchanged="TextBox1_TextChanged" AutoPostBack="True" style="margin-left: 0px"></asp:TextBox>
<br />
請輸入1~8,因為Northwind的Categories裡的CategoryID只有1~8</td>
</tr>
<tr>
<td class="style3">
DB out :
</td>
<td class="style4">
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="TextBox1" EventName="TextChanged" />
</Triggers>
</asp:UpdatePanel>
</td>
</tr>
</table>
</div>
</form>
</body>
============ 下面是C# 的部份 ==========================
protected void Page_Load(object sender, EventArgs e)
{
Label1.Visible = false;
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
Label1.Visible = true;
String strConn = @"Data Source=.\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True";
using (SqlConnection conn = new SqlConnection(strConn))
{
String strCmd = "Select CategoryID, CategoryName from Categories where categoryID=@categoryID";
using (SqlCommand cmd = new SqlCommand(strCmd, conn))
{
cmd.Parameters.AddWithValue("@categoryID", TextBox1.Text);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read()) //讀取資料之前要先呼叫read()的方法
{
Label1.Text = dr["CategoryName"].ToString();
}
conn.Close();
}
};
}
沒有留言:
張貼留言