帮助我识别代码中的错误 [英] help me identify the bug in my code
问题描述
我正在给我的代码降级,但是请帮助我找出错误.详细的解释将是完整的帮助.我正在做的是将从下拉列表中选择的值存储到变量中.现在,当我单击按钮时,变量中的值必须存储在数据库中,但是发生的事情是当我单击按钮时,出现此错误
hi i am giving small downgraded version of my code but please help me to identify the bug.a detailed explanation would be help full.what i am doing is i am storing selected value from a drop down list into an variable . now when i click button the value in variable must get stored in database but what is happening that when i click on button i get this error
The parameterized query '(@value nvarchar(4000))insert into abs2(vab2)values(@value)' expects the parameter '@value', which was not supplied.
当我调试时,我发现变量的值始终为null有人可以告诉我发生了什么
这是我的代码.请告诉我哪里出了错,应该怎么办以及为什么会发生?
第一个标记
when i debug i found value of variable to be always null can anybody tell me whats happening
here is my code.please tell where i went wrong and what should i do and why ithappens?
first markup
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"
onselectedindexchanged="DropDownList1_SelectedIndexChanged" Width="112px">
<asp:ListItem>value1</asp:ListItem>
<asp:ListItem>value2</asp:ListItem>
<asp:ListItem>value3</asp:ListItem>
<asp:ListItem>value4</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />
</div>
</form>
</body>
</html>
public partial class _Default : System.Web.UI.Page
{
string var;
SqlConnection conn;
SqlCommand cmd;
string str = ConfigurationManager.ConnectionStrings["cnstr"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
var = DropDownList1.SelectedValue;
}
protected void Button1_Click(object sender, EventArgs e)
{
conn = new SqlConnection(str);
cmd = new SqlCommand("insert into abs2(vab2)values(@value)",conn);
cmd.Parameters.AddWithValue("@value", var);
try
{
conn.Open();
int a = cmd.ExecuteNonQuery();
if (a > 0)
{
Response.Write("inserted");
}
else
{
Response.Write("failed");
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
conn.Close();
}
}
}
推荐答案
cmd = new SqlCommand("insert into abs2(vab2)values(@vab2)",conn);
cmd.Parameters.AddWithValue("@value", var);
您可以通过将var传递给查询来直接插入
you can insert direct by passing var to query
声明变量,如
declare variable like
var v= DropDownList1.SelectedValue;
cmd=new SqlCommand("insert into abs2(vab2)values(@vab2)",conn);
cmd.Parameters.AddWithValue("@value", v);
试试这个
Try this one
cmd = new SqlCommand("insert into abs2(vab2)values(@value)",conn);
cmd.Parameters.AddWithValue("@value", DropDownList1.SelectedValue);
这篇关于帮助我识别代码中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!