【发布时间】:2021-07-21 21:22:43
【问题描述】:
我正在尝试开发一个从 SQL 服务器接收数据的网站,然后在列表框和文本框上显示信息,当用户选择一个选项时,然后将数据插入数据库中的表中。
我的 ASP.NET 控件是:
<asp:ListBox ID="ListBox1" ClientIDMode="static" runat="server"></asp:ListBox>
<asp:Button ID="btnInsert" runat="server" Text="Start" OnClick="btnInsert_Click" />
我需要将数据加载到列表框,但不知道如何直接执行。要检索信息并查看其是否有效,我这样做了:
protected void Page_Load(object sender, EventArgs e){
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataReader reader = cmd.ExecuteReader();
GridView2.DataSource= reader;
GridView2.DataBind();
con.Close();
var nProject = GridView2.Rows.Count;
for (int b = 0; b < nProject ; b++)
{
ListBox1.Items.Add(GridView2.Rows[b].Cells[0].Text);
}
}
然后我尝试将所选信息设置为文本框,但没有任何反应(因为我设法将数据从文本框插入到 SQL Server INSERT):
protected void ListBox1_OnSelectedIndexChanged(object sender, System.EventArgs e)
{
TextBox2.Text = ListBox1.SelectedValue;
Response.Write("ListBox selectedIndexChanged");
}
通过单击按钮将信息发送回数据库:
protected void btnInsert_Click(object sender, EventArgs e)
{
var IP = "111.111.11";
txtStatus.Text = "Start";
txtProject.Text = "PR-02";
var indice = 0;
// This always returns "0"
if (ListBox1.SelectedItem != null)
{
indice = ListBox1.SelectedIndex;
}
txtProject.Text = indice.ToString();
// Sql INSERT works fine, but only with info manually created. I can't get the real info to work
SqlConnection con = new SqlConnection("****");
SqlCommand cmd = new SqlCommand(@"INSERT INTO [dbo].[table3]
([project]
,[user_task]
,[status]
,[ip]
,[location])
VALUES
('" + txtProject.Text + "', '" + txtUser.Text + "', '" + txtStatus.Text + "', '" + txtIP.Text + "', '" + txtLocation.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
【问题讨论】:
-
关于您的插入语句,always use parameters。
-
您为什么选择使用 ASP.NET Web 窗体开发新网站?现在是 2021 年——不要一开始就使用死的框架!有很多很棒的、更现代的选择:ASP.NET Core MVC、Blazor、ASP.NET Core Web API + SPA 框架等。
标签: c# asp.net sql-server webforms