C# 如何在ASP.net、sql server和c之间传递数据#
我正在尝试开发一个网站,它从SQLServer接收数据,然后在listbox和textbox上显示信息,当用户选择一个选项时,将数据插入数据库中的一个表中 我的ASP.NET控件是:C# 如何在ASP.net、sql server和c之间传递数据#,c#,asp.net,sql-server,webforms,C#,Asp.net,Sql Server,Webforms,我正在尝试开发一个网站,它从SQLServer接收数据,然后在listbox和textbox上显示信息,当用户选择一个选项时,将数据插入数据库中的一个表中 我的ASP.NET控件是: <asp:ListBox ID="ListBox1" ClientIDMode="static" runat="server"></asp:ListBox> <asp:Button ID="btnInsert&quo
<asp:ListBox ID="ListBox1" ClientIDMode="static" runat="server"></asp:ListBox>
<asp:Button ID="btnInsert" runat="server" Text="Start" OnClick="btnInsert_Click" />
通过单击按钮将信息发送回数据库:
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();
}
页面加载是每次调用服务器时首先运行的事件之一,这意味着它在BTN插入单击事件之前运行 这意味着您要在检查SelectedItem之前重新填充ListBox1,这就是为什么它总是返回“0” <>你必须考虑这一点,并使用类似之类的东西。
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack || Page.IsCallback) return;
(...)
}
很难理解您想要做什么,但是我认为如果您更正页面加载事件,ListBox1_OnSelectedIndexChanged是无用的
旁注:
- 您应该从尽可能使用语句开始(在SqlConnection和SqlCommand上)
- 请注意Sql注入,这可能是一个简单的测试程序,但您应该永远不要这样做:@“插入(…)值(“+txtProject.Text+”) 请改用参数:
-
<>你似乎在使用.NET框架和ASPX页面,你应该考虑使用更新的技术(.Net Core)。
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();
}
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack || Page.IsCallback) return;
(...)
}
using(SqlConnection con = new SqlConnection("****"))
using(SqlCommand cmd = new SqlCommand("INSERT INTO [dbo].[table3] ([project]) values (@project)", con))
{
cmd.Parameters.AddWithValue("@project", txtProject.Text);
}