Я искал онлайн ответы разных людей о том, как вставлять данные с помощью asp.net и C#, но до сих пор все разные вещи, которые я пробовал, ничего не делают, почему моя кнопка не делать что-либо, когда я нажимаю, чтобы вставить данные в мою БД? также, что я использую, чтобы различать текстовое поле и раскрывающийся список, мог бы я использовать ddl.selecteditem, который я сейчас использую, и это лучший способ? большинство исходных текстов онлайн и учебники, которые я рассматривал, имеют дело с gridviews, и я просто не смог эффективно перевести это на то, что мне нужно.Как вставить данные в DB
вот мой HTML
</td>
<td style="height: 51px; width: 377px; font-weight: bold;">
Project Tester
</td>
<td>
<asp:DropDownList ID="ddlTester" runat="server"
DataTextField="" Width="203px" DataBound="ddlTester_DataBound"
AutoPostBack="False">
</asp:DropDownList>
<asp:SqlDataSource runat="server" ID="SqlDataSource1" ConnectionString='<%$ ConnectionStrings:ProjectsAndTasksTestConnectionString %>'
SelectCommand="SELECT [TesterName] FROM [Users] ORDER BY [TesterName]">
</asp:SqlDataSource>
</td>
</tr>
<tr>
<td>
</td>
<td style="height: 51px; width: 377px; font-weight: bold;">
Project Name
</td>
<td>
<asp:TextBox ID="txtProjectName" runat="server" Width="200px"></asp:TextBox>
</td>
</tr>
<tr>
<td style="height: 51px">
</td>
<td style="height: 51px; width: 377px; font-weight: bold;">
Project Description</td>
<td style="height: 51px">
<asp:TextBox ID="txtProjectDesc" runat="server" TextMode="MultiLine" Height="105px" Width="237px"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td style="height: 51px; width: 377px; font-weight: bold;">
Assigned Date</td>
<td>
<asp:TextBox ID="txtStartDate" runat="server" Width="200px"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td style="height: 51px; width: 377px; font-weight: bold;">
Due Date</td>
<td>
<asp:TextBox ID="txtEndDate" runat="server" Width="200px"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td style="height: 51px; width: 377px; font-weight: bold;">
Project Platform</td>
<td>
<asp:TextBox ID="TxtProjectPlatform" runat="server" Width="200px"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td style="height: 51px; width: 377px; font-weight: bold;">
BIOS</td>
<td>
<asp:TextBox ID="TxtBios" runat="server" Width="200px"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td style="height: 51px; width: 377px; font-weight: bold;">
PCH</td>
<td>
<asp:TextBox ID="TxtPch" runat="server" Width="200px"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td style="height: 51px; width: 377px; font-weight: bold;">
PROC</td>
<td>
<asp:TextBox ID="TxtProc" runat="server" Width="200px"></asp:TextBox>
</td>
</tr>
<tr>
<td>
</td>
<td style="height: 51px; width: 377px; font-weight: bold;">
Forward To</td>
<td>
<asp:DropDownList ID="employeeEmailDropDownList" runat="server"
Visible="True"
DataSourceID="SqlDataSource2" DataTextField="EmailAddress" DataValueField="EmailAddress" Width="203px">
</asp:DropDownList>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ProjectsAndTasksTestConnectionString %>"
SelectCommand="SELECT [EmailAddress] FROM [Users] ORDER BY [TesterName]"></asp:SqlDataSource></td>
</tr>
<tr>
<td>
</td>
<td>
</td>
<td>
</td>
</tr>
<tr>
<td>
</td>
<td style="width: 377px">
</td>
<td>
<asp:Button ID="Button1" runat="server" onclick="CreateProject_Click"
Text="Create Project" Font-Bold="true" Height="45px" Width="198px" />
<asp:Label ID="errorLabel" runat="server" ForeColor="Red"></asp:Label>
<asp:Label ID="successLabel" runat="server" ForeColor="Green"></asp:Label>
</td>
</tr>
<tr>
<td style="height: 29px">
</td>
<td style="height: 29px; width: 377px;">
</td>
<td style="height: 29px">
</td>
</tr>
</table>
</asp:Panel>
</asp:Content>
и здесь является C# У меня есть
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Project_Set
{
public partial class Projects_AddProject : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Populate1();
}
}
protected void ddlTester_DataBound(object sender, EventArgs e)
{
//Inserting an item in the 0 index of the DDL named "-Select-"
//which will navigate the user to select an item
ddlTester.Items.Insert(0, new ListItem("-Select-"));
}
public void Populate1()
{
if (!IsPostBack)
{
string connetionString = "Data Source=JVANCEX-MOBL2;Initial Catalog=ProjectsAndTasksTest; Trusted_Connection=True;";
SqlCommand cmd = new SqlCommand("SELECT TesterName AS FullName FROM [Users]", new SqlConnection(ConfigurationManager.ConnectionStrings["ProjectsAndTasksTestConnectionString"].ConnectionString));
using (SqlConnection cnn = new SqlConnection(connetionString))
{
cmd.Connection.Open();
SqlDataReader ddlValues;
ddlValues = cmd.ExecuteReader();
ddlTester.DataSource = ddlValues;
ddlTester.DataValueField = "FullName";
ddlTester.DataTextField = "FullName";
ddlTester.DataBind();
cmd.Connection.Close();
//cmd.Connection.Dispose();
}
}
}
public void CreateProject_Click(object sender, EventArgs e)
{
if (!IsPostBack)
{
string connetionString = "Data Source=JVANCEX-MOBL2;Initial Catalog=ProjectsAndTasksTest; Trusted_Connection=True;";
string insStmt = "INSERT INTO Projects (TesterName, ProjectName, ProjectDescription, DueDate, DateAssigned, Platform) values (@TesterName, @ProjectName,@ProjectDesc, @DueDate, @DateAssigned, @Platform)";
using (SqlConnection cnn = new SqlConnection(connetionString))
{
cnn.Open();
SqlCommand insCmd = new SqlCommand(insStmt, cnn);
insCmd.Parameters.AddWithValue("@ProjectName", txtProjectName);
insCmd.Parameters.AddWithValue("@ProjectDesc", txtProjectDesc);
insCmd.Parameters.AddWithValue("@TesterName", ddlTester.SelectedItem);
insCmd.Parameters.AddWithValue("@DateAssigned", txtStartDate);
insCmd.Parameters.AddWithValue("@DueDate", txtEndDate);
insCmd.Parameters.AddWithValue("@Platform", TxtProjectPlatform);
//insCmd.Parameters.AddWithValue("@Bios", TxtBios.Text);
//insCmd.Parameters.AddWithValue("@Pch", TxtPch.Text);
//insCmd.Parameters.AddWithValue("@Proc", TxtProc.Text);
insCmd.ExecuteNonQuery();
cnn.Close();
//MessageBox.Show(affectedRows + " Project Created!");
}
}
}
Я знаю, что нужно использовать .Parameters для защиты от возможного введения MySQL, но помимо этого я новый для asp.net и C#.
для вашего первого запроса вы можете сделать это гораздо быстрее, используя 'DataTable' и встроенный запрос или storedproc как well – MethodMan
Я также предлагаю вам пройти через код. у вас есть какие-либо события нажатия кнопки или какие-либо другие элементы управления, которые будут генерировать 'autopostback', ваша логика выглядит немного подозрительной, а также« оберните ваш код .ExecuteNonQuert »вокруг' try {} catch (DbException ex) {} ', чтобы ловушка/отчет любые ошибки, которые могут произойти. Не предполагайте, что любой из запросов всегда будет успешно выполнен. – MethodMan