C# 从多个文本框更新SQL Server

C# 从多个文本框更新SQL Server,c#,sql-server,visual-studio,textbox,sql-update,C#,Sql Server,Visual Studio,Textbox,Sql Update,我需要从多个文本框更新SQL Server数据库。我有两个问题: 我的代码有什么问题可能我的ID列有问题?它是自动递增的 我的位置是否足以在Employee表中找到精确匹配项以进行更新 Employee包含7列: Id (int), Name (nvarchar(max)), LastName(nvarcharmax), Age(int), Dep_nt(nvarchar(max)), Profession (nvarchar(max)), Salary (real). 我的代码: priva

我需要从多个文本框更新SQL Server数据库。我有两个问题:

我的代码有什么问题可能我的ID列有问题?它是自动递增的

我的位置是否足以在Employee表中找到精确匹配项以进行更新

Employee包含7列:

Id (int), Name (nvarchar(max)), LastName(nvarcharmax), Age(int), Dep_nt(nvarchar(max)), Profession (nvarchar(max)), Salary (real).
我的代码:

private void button0_Click(object sender, RoutedEventArgs e)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        var sql = String.Format("UPDATE Employee SET Name = @Name, LastName = @LastName, Age = @Age, Dep_nt = @Dep_nt, Profession = @Profession, Salary = @Salary WHERE ID = @ID", connection);

        SqlCommand command = new SqlCommand(sql, connection);

        command.Parameters.AddWithValue("@Name", NameF.Text);
        command.Parameters.AddWithValue("@LastName", LastNameF.Text);
        command.Parameters.AddWithValue("@Age", Convert.ToInt32(AgeF.Text)); 
        command.Parameters.AddWithValue("@Dep_nt", DepartmentF.Text);
        command.Parameters.AddWithValue("@Profession", ProfessionF.Text);
        command.Parameters.AddWithValue("@Salary", Convert.ToDouble(SalaryF.Text));

        //SqlParameter param = command.Parameters.Add("@ID", SqlDbType.Int, 0, "ID");
        //param = command.Parameters.Add("@ID", SqlDbType.Int, 0, "ID");
        //param.SourceVersion = DataRowVersion.Original;

        adapter.UpdateCommand = command;

        DataTable dt = new DataTable();
        adapter.Fill(dt);

        Ep.ItemsSource = dt.DefaultView;

        connection.Close();
    }
}
目前,我的代码完全不起任何作用

我的申请的完整代码:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace BigCompanyinc
{
    /// <summary>
    /// Логика взаимодействия для MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        Logic L = new Logic();
        string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Hospital;Integrated Security=True;Pooling=False";

        SqlDataAdapter adapter = new SqlDataAdapter();

        public MainWindow()
        {
            InitializeComponent();
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand command = new SqlCommand("SELECT DepartmentName FROM Department ", connection);
            adapter.SelectCommand = command;
            DataTable dataTable = new DataTable();
            adapter.Fill(dataTable);
            List<string> DepartmentNames = new List<string>();
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                String DepartmentName = Convert.ToString(dataTable.Rows[i]["DepartmentName"]);
                DepartmentNames.Add(DepartmentName);
            }
            Department4.ItemsSource = DepartmentNames;
            DepartmentF.ItemsSource = DepartmentNames;
            DpListBox.ItemsSource = dataTable.DefaultView;
            L.InitReadOnly(true, Name4, LastName4, Age4, Department4, Profession4, Salary4);
            L.InitReadOnly(true, NameF, LastNameF, AgeF, DepartmentF, ProfessionF, SalaryF);
            MessageBox.Show("Выберите департамент, чтобы начать работу.");
        }

        /// <summary>
        /// Добавить новый департамент
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button2_Click(object sender, RoutedEventArgs e)
        {
            var sql = String.Format("INSERT INTO Department (DepartmentName) " + "VALUES (N'{0}')",
            Name7.Text);
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlCommand command = new SqlCommand(sql, connection);
                command.ExecuteNonQuery();
                command = new SqlCommand(@"UPDATE Deparment SET DepartmentName = @DepartmentName WHERE ID =@ID", connection);
                command.Parameters.Add("@DepartmentName", SqlDbType.NVarChar, -1, "DepartmentName");
                SqlParameter param = command.Parameters.Add("@ID", SqlDbType.Int, 0, "ID");
                param.SourceVersion = DataRowVersion.Original;
                adapter.UpdateCommand = command;
                DataTable dataTable = new DataTable();
                adapter.Fill(dataTable);
                DpListBox.ItemsSource = dataTable.DefaultView;
                connection.Close();
            }
        }

        /// <summary>
        /// Выбран новый элемент ListBox для коллекции департаментов
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DpListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            L.InitReadOnly(false, Name4, LastName4, Age4, Department4, Profession4, Salary4);
            L.InitReadOnly(false, NameF, LastNameF, AgeF, DepartmentF, ProfessionF, SalaryF);

            SqlConnection connection = new SqlConnection(connectionString);
            connection.Open();
            SqlDataAdapter adapter = new SqlDataAdapter();
            DataRowView dataRowView = DpListBox.SelectedItem as DataRowView;

            string value = "";

            if (dataRowView != null)
            {
                value = dataRowView.Row["DepartmentName"] as string;
            }
            SqlCommand command = new SqlCommand($@"SELECT * FROM Employee WHERE Dep_nt='" + value + "'", connection);
            adapter.SelectCommand = command;
            DataTable dataTable1 = new DataTable();
            adapter.Fill(dataTable1);
            Ep.ItemsSource = dataTable1.DefaultView;
            connection.Close();
        }

        private void Button1_Click(object sender, RoutedEventArgs e)
        {
            var sql = String.Format("INSERT INTO Employee (Name, LastName, Age, Dep_nt, Profession, Salary) " + "VALUES (N'{0}', '{1}', '{2}', '{3}', '{4}', '{5}')", Name4.Text, LastName4.Text, Age4.Text, Department4.Text, Profession4.Text, Salary4.Text);
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlCommand command = new SqlCommand(sql, connection);
                command.ExecuteNonQuery();

                SqlConnection connection1 = new SqlConnection(connectionString);
                SqlDataAdapter adapter = new SqlDataAdapter();
                DataRowView dataRowView = DpListBox.SelectedItem as DataRowView;

                string value = "";

                if (dataRowView != null)
                {
                    value = dataRowView.Row["DepartmentName"] as string;
                }
                SqlCommand command1 = new SqlCommand($@"SELECT * FROM Employee WHERE Dep_nt='" + value + "'", connection1);
                adapter.SelectCommand = command1;
                DataTable dataTable1 = new DataTable();
                adapter.Fill(dataTable1);
                Ep.ItemsSource = dataTable1.DefaultView;
                connection.Close();
            }
        }

        private void button0_Click(object sender, RoutedEventArgs e)
        {

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();
                var sql = String.Format("UPDATE Employee SET Name = @Name, LastName = @LastName, Age = @Age, Dep_nt = @Dep_nt, Profession = @Profession, Salary = @Salary WHERE ID = @ID", connection);
                SqlCommand command = new SqlCommand(sql, connection);
                command.Parameters.AddWithValue("@Name", NameF.Text);
                command.Parameters.AddWithValue("@LastName", LastNameF.Text);
                command.Parameters.AddWithValue("@Age", Convert.ToInt32(AgeF.Text)); 
                command.Parameters.AddWithValue("@Dep_nt", DepartmentF.Text);
                command.Parameters.AddWithValue("@Profession", ProfessionF.Text);
                command.Parameters.AddWithValue("@Salary", Convert.ToDouble(SalaryF.Text));

                SqlParameter param = command.Parameters.Add("@ID", SqlDbType.Int, 0, "ID");
                param = command.Parameters.Add("@ID", SqlDbType.Int, 0, "ID");
                param.SourceVersion = DataRowVersion.Original;
                adapter.UpdateCommand = command;
                DataTable dt = new DataTable();
                adapter.Fill(dt);
                Ep.ItemsSource = dt.DefaultView;
                connection.Close();
            }
        }

        private void Ep_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            L.InitReadOnly(false, NameF, LastNameF, AgeF, DepartmentF, ProfessionF, SalaryF);

            DataRowView dataRowView = Ep.SelectedItem as DataRowView;

            if (dataRowView != null)
            {
                NameF.Text = dataRowView.Row["Name"] as string;
                LastNameF.Text = dataRowView["LastName"] as string;
                AgeF.Text = Convert.ToString(dataRowView["Age"]);
                DepartmentF.Text = dataRowView["Dep_nt"] as string;
                ProfessionF.Text = dataRowView["Profession"] as string;
                SalaryF.Text = Convert.ToString(dataRowView["Salary"]);
            }
            else
            {
                NameF.Text = "";
                LastNameF.Text = "";
                AgeF.Text = "";
                DepartmentF.Text = "";
                ProfessionF.Text = "";
                SalaryF.Text = "";
            }
        }
    }
}
我使用WPF。XAML代码:

<Window x:Name="Staff" x:Class="BigCompanyinc.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:BigCompanyinc"
        mc:Ignorable="d"
        Title="Staff" Height="513.5" Width="991.833" ResizeMode="NoResize"
        Icon="icon1.ico">
    <Grid Height="504" VerticalAlignment="Top" Margin="10,0,-23,-19">
        <Grid.RowDefinitions>
        </Grid.RowDefinitions>
        <TextBox x:Name="NameF" HorizontalAlignment="Left" Margin="164,418,0,0" VerticalAlignment="Top" Width="120" Height="22" IsReadOnly="False"/>
        <TextBox x:Name="LastNameF" HorizontalAlignment="Left" Margin="294,418,0,0" VerticalAlignment="Top" Width="120" Height="22" IsReadOnly="False"/>
        <TextBox x:Name="AgeF" HorizontalAlignment="Left" Margin="424,418,0,0" VerticalAlignment="Top" Width="120" Height="22" IsReadOnly="False"/>
        <ComboBox x:Name="DepartmentF" HorizontalAlignment="Left" Margin="554,418,0,0" VerticalAlignment="Top" Width="120" Height="22" IsReadOnly="False"/>
        <TextBox x:Name="ProfessionF" HorizontalAlignment="Left" Margin="684,418,0,0" VerticalAlignment="Top" Width="120" Height="22" IsReadOnly="False"/>
        <TextBox x:Name="SalaryF" HorizontalAlignment="Left" Margin="814,418,0,0" VerticalAlignment="Top" Width="120" Height="22" IsReadOnly="False"/>

        <Button  x:Name="button0" HorizontalAlignment="Left" Margin="164,448,0,0" VerticalAlignment="Top" Width="120" Height="22" Background="LightBlue" 
                 Content="Изменить данные" Click="button0_Click"/>

        <TextBox x:Name="Name1" HorizontalAlignment="Left" Margin="164,386,0,0" VerticalAlignment="Top" Width="120" Height="22" Text="Имя" IsReadOnly="True"/>
        <TextBox x:Name="LastName1" HorizontalAlignment="Left" Margin="294,386,0,0" VerticalAlignment="Top" Width="120" Height="22" Text="Фамилия" IsReadOnly="True"/>
        <TextBox x:Name="Age1" HorizontalAlignment="Left" Margin="424,386,0,0" VerticalAlignment="Top" Width="120" Height="22" Text="Возраст" IsReadOnly="True"/>
        <TextBox x:Name="Department1" HorizontalAlignment="Left" Margin="554,386,0,0" VerticalAlignment="Top" Width="120" Height="22" Text="Департамент" IsReadOnly="True"/>
        <TextBox x:Name="Profession1" HorizontalAlignment="Left" Margin="684,386,0,0" VerticalAlignment="Top" Width="120" Height="22" Text="Профессия" IsReadOnly="True"/>
        <TextBox x:Name="Salary1" HorizontalAlignment="Left" Margin="814,386,0,0" VerticalAlignment="Top" Width="120" Height="22" Text="Заработная плата" IsReadOnly="True"/>
        <TextBox x:Name="Header1" HorizontalAlignment="Left" Margin="164,39,0,0" VerticalAlignment="Top" Width="250" Height="22" Text="Добавить сотрудника" IsReadOnly="True"/>
        <TextBox x:Name="Name4" HorizontalAlignment="Left" Margin="164,99,0,0" VerticalAlignment="Top" Width="120" Height="22" IsReadOnly="False"/>
        <TextBox x:Name="LastName4" HorizontalAlignment="Left" Margin="294,99,0,0" VerticalAlignment="Top" Width="120" Height="22" IsReadOnly="False"/>
        <TextBox x:Name="Age4" HorizontalAlignment="Left" Margin="424,99,0,0" VerticalAlignment="Top" Width="120" Height="22" IsReadOnly="False"/>
        <ComboBox x:Name="Department4" HorizontalAlignment="Left" Margin="554,99,0,0" VerticalAlignment="Top" Width="120" Height="22" IsReadOnly="False"/>
        <TextBox x:Name="Profession4" HorizontalAlignment="Left" Margin="684,99,0,0" VerticalAlignment="Top" Width="120" Height="22" IsReadOnly="False"/>
        <TextBox x:Name="Salary4" HorizontalAlignment="Left" Margin="814,99,0,0" VerticalAlignment="Top" Width="120" Height="22" IsReadOnly="False"/>
        <TextBox x:Name="Name5" HorizontalAlignment="Left" Margin="164,69,0,0" VerticalAlignment="Top" Width="120" Height="22" Text="Имя" IsReadOnly="True"/>
        <TextBox x:Name="LastName5" HorizontalAlignment="Left" Margin="294,69,0,0" VerticalAlignment="Top" Width="120" Height="22" Text="Фамилия" IsReadOnly="True"/>
        <TextBox x:Name="Age5" HorizontalAlignment="Left" Margin="424,69,0,0" VerticalAlignment="Top" Width="120" Height="22" Text="Возраст" IsReadOnly="True"/>
        <TextBox x:Name="Department5" HorizontalAlignment="Left" Margin="554,69,0,0" VerticalAlignment="Top" Width="120" Height="22" Text="Департамент" IsReadOnly="True"/>
        <TextBox x:Name="Profession5" HorizontalAlignment="Left" Margin="684,69,0,0" VerticalAlignment="Top" Width="120" Height="22" Text="Профессия" IsReadOnly="True"/>
        <TextBox x:Name="Salary5" HorizontalAlignment="Left" Margin="814,69,0,0" VerticalAlignment="Top" Width="120" Height="22" Text="Заработная плата" IsReadOnly="True"/>
        <Button  x:Name="button1" HorizontalAlignment="Left" Margin="164,129,0,0" VerticalAlignment="Top" Width="120" Height="22" Background="LightBlue" 
            Content="Добавить" Click="Button1_Click"/>
        <TextBox x:Name="Header2" HorizontalAlignment="Left" Margin="10,39,0,0" VerticalAlignment="Top" Width="144" Height="22" Text="Добавить департамент" IsReadOnly="True"/>
        <TextBox x:Name="Name6" HorizontalAlignment="Left" Margin="10,69,0,0" VerticalAlignment="Top" Width="144" Height="22" Text="Название" IsReadOnly="True"/>
        <TextBox x:Name="Name7" HorizontalAlignment="Left" Margin="10,99,0,0" VerticalAlignment="Top" Width="144" Height="22" IsReadOnly="False"/>
        <Button  x:Name="button2" HorizontalAlignment="Left" Margin="10,129,0,0" VerticalAlignment="Top" Width="70" Height="22" Background="LightBlue" 
            Content="Добавить" Click="Button2_Click"/>

        <TextBox x:Name="Department2" HorizontalAlignment="Left" Margin="10,12,0,0" VerticalAlignment="Top" Width="144" Height="22" Text="Департамент" IsReadOnly="True"/>
        <ListBox SelectedItem="DepartmentName" x:Name="DpListBox" HorizontalAlignment="Left" Margin="10,165,0,138" Width="144" SelectionChanged="DpListBox_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding DepartmentName}"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <ListView x:Name="Ep" HorizontalAlignment="Left" Height="201" Margin="164,165,0,0" VerticalAlignment="Top" Width="791" SelectionChanged="Ep_SelectionChanged">
            <ListView.View>
                <GridView>
                    <GridViewColumn Width="130" Header="Имя" DisplayMemberBinding="{Binding Name}"/>
                    <GridViewColumn Width="130" Header="Фамилия" DisplayMemberBinding="{Binding LastName}"/>
                    <GridViewColumn Width="130" Header="Возраст" DisplayMemberBinding="{Binding Age}"/>
                    <GridViewColumn Width="130" Header="Департамент" DisplayMemberBinding="{Binding Dep_nt}"/>
                    <GridViewColumn Width="130" Header="Профессия" DisplayMemberBinding="{Binding Profession}"/>
                    <GridViewColumn Width="130" Header="Заработная плата" DisplayMemberBinding="{Binding Salary}"/>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>
根据文件:

INSERT、SELECT INTO或bulk copy语句完成后, @@标识包含由生成的最后一个标识值 陈述如果该语句不影响任何具有标识的表 列,@@IDENTITY返回NULL

您尚未在连接中执行插入操作,因此@@IDENTITY的值将为空


您需要像其他参数一样,将要更新的ID的值作为参数传递。将ID=@@IDENTITY更改为ID=@ID,然后再添加一个参数及其值我无法告诉您该行是什么,因为我不知道您的应用程序中ID值在哪里。

此部分的正确代码:

private void button0_Click(object sender, RoutedEventArgs e)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        DataRowView dataRowView = Ep.SelectedItem as DataRowView;
        cmd =  new SqlCommand("UPDATE Employee SET Name = @Name, LastName = @LastName, Age = @Age, Dep_nt = @Dep_nt, Profession = @Profession, Salary = @Salary WHERE ID = @ID", connection);
        connection.Open();
        cmd.Parameters.AddWithValue("@ID", dataRowView.Row["Id"] as Nullable<int>);
        cmd.Parameters.AddWithValue("@Name", NameF.Text);
        cmd.Parameters.AddWithValue("@LastName", LastNameF.Text);
        cmd.Parameters.AddWithValue("@Age", Convert.ToInt32(AgeF.Text)); 
        cmd.Parameters.AddWithValue("@Dep_nt", DepartmentF.Text);
        cmd.Parameters.AddWithValue("@Profession", ProfessionF.Text);
        cmd.Parameters.AddWithValue("@Salary", Convert.ToDouble(SalaryF.Text));
        cmd.ExecuteNonQuery();
        DataTable dt = new DataTable();
        adapter.UpdateCommand = cmd;
        adapter.Fill(dt);
        Ep.ItemsSource = dt.DefaultView;
        connection.Close();
    }
}

我真的不知道。我希望它能在Employee中找到更新的正确行,也许ID=@ID会更好,你能给出更准确的例子吗,正如我所了解的,我应该将所有addwithvalue更改为addEp-listview元素,Employee连接到该元素。我已经使用了command.parameter.Add,但我禁用了它,因为它没有帮助。我正在visual Studio中使用C代码。我不明白你的意思,所以我添加了完整的代码。如果有,请检查一下time@Fallingsappy你的更新声明。它正在使用@@IDENTITY:var sql=String.FormatUPDATE员工集名称=@Name,LastName=@LastName,Age=@Age,Dep\u nt=@Dep\u nt,Profession=@Profession,Salary=@Salary,其中ID=@@IDENTITY,connection;我得到它并更改了它ID=@ID,但它什么也没做我的意思是,我的代码仍然没有更改employee表的值