Я нахожусь в c # ASP.NET, и я новичок во всем этом.пытаюсь научить себя, но я одержим чем-то, что, я полагаю, должно быть простым.Я не смог найти ответ здесь с поисками, потому что, думаю, я не знаю подходящего способа описать то, что я ищу.Поэтому я в последний раз прибегаю к тому, чтобы вас уговаривать за ответ.
Пожалуйста, будьте очень просты, я новичок, но очень хочу.
У меня есть специалист по обработке данных, возвращающий X результатов из базы данных (MSSQL) - каждый результат содержит некоторую информацию, а затем 2 текстовых поля и кнопку.я хочу, чтобы они могли вводить некоторую информацию в каждое поле, нажимать кнопку, а затем она вставляется обратно в мою базу данных SQL.
Я хочу получить текстовые результаты из каждого текстового поля вместе с идентификатором (aЗначение sql, возвращаемое из результатов списка данных), чтобы пойти с ним (чтобы моя вставка знала, из каких результатов это)
, поэтому моя страница выглядит как
text 1 - TEXTBOX - TEXTBOX - BUTTON text2 - и т. Д. И т. Д.
, если парень заполняет текстовые поля text 2 и нажимает кнопку text2, я вставляю (textbox1.text, textbox2.text, "text 2") в мою базу данных
thisэто то, что у меня есть в моем коде для списка данных до сих пор:
protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{
Button Button2b = (Button)e.Item.FindControl("Button2");
TextBox TextBox2b = (TextBox)e.Item.FindControl("TextBox2");
TextBox TextBox3b = (TextBox)e.Item.FindControl("TextBox3");
SqlDataSource commentinsert = new SqlDataSource();
commentinsert.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
commentinsert.InsertCommandType = SqlDataSourceCommandType.Text;
commentinsert.InsertCommand = "INSERT INTO ocomments (cuser, date, ip, blogid, text) VALUES (@cuser, @date, @ip, @blogid, @text)";
commentinsert.InsertParameters.Add("cuser", TextBox2b.Text);
commentinsert.InsertParameters.Add("date", DateTime.Now.ToString());
commentinsert.InsertParameters.Add("ip", Request.UserHostAddress.ToString());
commentinsert.InsertParameters.Add("blogid", "16");
commentinsert.InsertParameters.Add("text", TextBox3b.Text);
commentinsert.Insert();
}
вот соответствующий файл данных в моем aspx
<asp:DataList ID="DataList1" runat="server" DataKeyField="id"
DataSourceID="SqlDataSource1" style="width:700px;" onitemdatabound="DataList1_ItemDataBound"
onitemcommand="DataList1_ItemCommand">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Eval("subject") %>' style="font-size:25pt;font-family:Tahoma;"></asp:Label>
<asp:Label ID="Label2" runat="server" Text='<%# Eval("auser", " - {0}") %>' style="font-size:15pt;color:#74daf8;font-family:Tahoma;"></asp:Label>
<br />
<hr width="80%" size="1" NOSHADE color="#343a68" />
<asp:Label style="font-size:14pt;font-family:Tahoma;font-weight:normal;" ID="Label3" runat="server" Text='<%# Eval("body") %>' />
<asp:HyperLink ID="HyperLink5" runat="server"
NavigateUrl='<%# Eval("id", "http://domain.com/?id={0}#{0}") %>'
Visible="False">edit</asp:HyperLink>
<br />
<span style="float:right;">
<asp:HyperLink ID="HyperLink7" runat="server" style="cursor:pointer;font-family:Tahoma;
font-size:12pt;color:White;"># comments - add a comment</asp:HyperLink>
</span>
<br />
<asp:Panel ID="Panel2" runat="server" style="display:none;width:600px;
background-color:Black;margin: 10px 0 10px 10px;padding: 5px 0 10px 10px;">
your name:
<br />
<asp:TextBox ID="TextBox2" runat="server" Width="250px"></asp:TextBox>
<br />
your comment:
<br />
<asp:TextBox ID="TextBox3" runat="server" Width="550px" height="150px" TextMode="MultiLine"></asp:TextBox>
<br />
<asp:Button ID="Button2" runat="server"
Text="Send Comment" Width="200px" Height="35px" Font-Bold="False" Font-Names="tahoma"
Font-Size="17pt" CommandArgument='<%# Eval("id") %>' />
</asp:Panel>
<hr width="30%" size="1" align="right" NOSHADE color="#696969" />
</ItemTemplate>
</asp:DataList>
и вот ошибка, которую я получаю, когда нажимаюкнопку отправки комментария, даже если у меня есть текст в текстовых полях, я пытаюсь получить данные из:
Ошибка сервера в приложении '/'.В экземпляре объекта не задана ссылка на объект.
, пожалуйста, помогите!
РЕДАКТИРОВАТЬ: пробовал следующий код в предложении пользователя, но я получаю точно такую же ошибку.
Control panelControl = e.Item.FindControl("Panel2");
Button Button2b = panelControl.FindControl("Button2") as Button;
TextBox TextBox2b = panelControl.FindControl("TextBox2") as TextBox;
TextBox TextBox3b = panelControl.FindControl("TextBox3") as TextBox;
SqlDataSource commentinsert = new SqlDataSource();
commentinsert.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
commentinsert.InsertCommandType = SqlDataSourceCommandType.Text;
commentinsert.InsertCommand = "INSERT INTO ocomments (cuser, date, ip, blogid, text) VALUES (@cuser, @date, @ip, @blogid, @text)";
commentinsert.InsertParameters.Add("cuser", TextBox2b.Text);
commentinsert.InsertParameters.Add("date", DateTime.Now.ToString());
commentinsert.InsertParameters.Add("ip", Request.UserHostAddress.ToString());
commentinsert.InsertParameters.Add("blogid", Button2b.CommandArgument.ToString());
commentinsert.InsertParameters.Add("text", TextBox3b.Text);
commentinsert.Insert();