-
新建数据库TestDB,新建表UserInfo,如下图:
2.创建WinForm项目
第一步:在App.config中添加数据库连接字符串:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="SqlConn" connectionString="server=.;uid=sa;pwd=xxxxxx;database=TestDB"/>
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
</configuration>
第二步:创建静态类SqlHelper,用于返回连接字符串
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace UserInfoManagerMyPractice
{
class SqlHelper
{
public static string GetSqlConnectionString()
{
return ConfigurationManager.ConnectionStrings["SqlConn"].ConnectionString;
}
}
}
第三步:根据UserInfo表,创建对应的UserInfo类:
class UserInfo
{
public int UserId { get; set; }
public string UserName { get; set; }
public int UserAge { get; set; }
public DateTime createdDate { get; set; }
public string UserPwd { get; set; }
public DateTime LastErrorDateTime { get; set; }
public int ErrorTimes { get; set; }
public int DelFlg { get; set; }
}
第四步:在主窗口上添加一个DataGridView和一个Button:
第五步:添加主窗口载入时的处理:
private void Form1_Load(object sender, EventArgs e)
{
LoadUserInfos();
}
private void LoadUserInfos()
{
string connStr = SqlHelper.GetSqlConnectionString();
// 把读取到的数据转换成类并存入List中,作为DataGridView的数据源
List<UserInfo> userInfoList = new List<UserInfo>();
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using(SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"SELECT [UserId]
,[UserName]
,[UserAge]
,[CreatedDate]
,[UserPwd]
,[LastErrorDateTime]
,[ErrorTimes]
,[DelFlag]
FROM [TestDB].[dbo].[UserInfo]";
using (SqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read())
{
UserInfo user = new UserInfo();
user.UserId = int.Parse(reader["UserId"].ToString());
user.UserName = reader["UserName"] == DBNull.Value ? string.Empty : reader["UserName"].ToString();
user.UserAge = int.Parse(reader["UserAge"].ToString());
user.createdDate = DateTime.Parse(reader["CreatedDate"].ToString());
user.UserPwd = reader["UserPwd"].ToString();
user.LastErrorDateTime = DateTime.Parse(reader["LastErrorDateTime"].ToString());
user.ErrorTimes = int.Parse(reader["ErrorTimes"].ToString());
user.DelFlg = int.Parse(reader["DelFlag"].ToString());
userInfoList.Add(user);
}
}
}
}
this.dataGridView1.DataSource = userInfoList;
}
运行程序,效果如下图:
第六步:实现点击“软”删除一列,并点击保存按钮后生效:
根据DelFlg字段中的值,确定该行数据是否已被删除
private void button1_Click(object sender, EventArgs e)
{
// 首先获得当前用户所选择的行
var rows = this.dataGridView1.SelectedRows;
if (rows.Count <= 0)
{
MessageBox.Show("请选择要删除的行");
}
StringBuilder sqlSb = new StringBuilder();
List<SqlParameter> parameters = new List<SqlParameter>();
for (int i = 0; i < rows.Count; i++)
{
sqlSb.Append("update UserInfo set DelFlag=1 where UserId=@UserId" + i + ";");
SqlParameter parameter = new SqlParameter(@"UserId" + i, SqlDbType.Int);
parameter.Value = int.Parse(rows[i].Cells["UserId"].Value.ToString());
parameters.Add(parameter);
}
// 根据主键进行“删除”操作
using (SqlConnection conn = new SqlConnection(SqlHelper.GetSqlConnectionString()))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = sqlSb.ToString();
cmd.Parameters.AddRange(parameters.ToArray());
cmd.ExecuteNonQuery();
// 刷新数据显示
LoadUserInfos();
}
}
}
另:
1.使用SqlDataAdapter的方法如下:
#region 查询按钮功能的实现
private void SearchButton_Click(object sender, EventArgs e)
{
string connStr = SQLHelper.GetSqlConnectionString();
string sqlText = @"SELECT [AddressID]
,[AddressLine1]
,[City]
,[StateProvince]
,[CountryRegion]
,[PostalCode]
,[ModifiedDate]
FROM [AdventureWorksLT2008R2].[SalesLT].[Address]";
List<string> whereList = new List<string>();
List<SqlParameter> parameters = new List<SqlParameter>();
if (!string.IsNullOrEmpty(this.StateProvinceTXT.Text.Trim()))
{
whereList.Add(" StateProvince like @StateProvince ");
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@StateProvince";
parameter.Value = "%" + this.StateProvinceTXT.Text + "%";
parameters.Add(parameter);
}
if (!string.IsNullOrEmpty(this.AddressTXT.Text.Trim()))
{
whereList.Add(" AddressLine1 like @AddressLine1 ");
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@AddressLine1";
parameter.Value = "%" + this.AddressTXT.Text + "%";
parameters.Add(parameter);
}
if (whereList.Count > 0)
{
sqlText += " WHERE " + string.Join(" and ", whereList);
}
List<Address> addressList = new List<Address>();
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlText, SQLHelper.GetSqlConnectionString()))
{
adapter.SelectCommand.Parameters.AddRange(parameters.ToArray());
DataTable dt = new DataTable();
adapter.Fill(dt);
foreach (DataRow dataRow in dt.Rows)
{
Address address = new Address();
address.AddressLine = dataRow["AddressLine1"].ToString();
address.City = dataRow["City"].ToString();
address.StateProvince = dataRow["StateProvince"].ToString();
address.CountryRegion = dataRow["CountryRegion"].ToString();
address.PostalCode = dataRow["PostalCode"].ToString();
address.ModifiedDate = DateTime.Parse(dataRow["ModifiedDate"].ToString( ));
addressList.Add(address);
}
this.AddressGridView.DataSource = addressList;
}
}
#endregion
2.使用SqlDataReader的方法:
#region 双击GridView中一列的处理方法
private void AddressGridView_DoubleClick(object sender, EventArgs e)
{
if (this.AddressGridView.SelectedRows.Count <= 0)
{
return;
}
int selectedRowID = int.Parse(this.AddressGridView.SelectedRows[0].Cells[0].Value.ToString());
using (SqlConnection conn = new SqlConnection(SQLHelper.GetSqlConnectionString()))
{
conn.Open();
using (SqlCommand cmd = conn.CreateCommand())
{
cmd.CommandText = @"SELECT [AddressID]
,[AddressLine1]
,[City]
,[StateProvince]
,[CountryRegion]
,[PostalCode]
,[ModifiedDate]
FROM [AdventureWorksLT2008R2].[SalesLT].[Address] WHERE [AddressID]=@AddressID";
SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@AddressID";
parameter.Value = selectedRowID;
cmd.Parameters.Add(parameter);
using (SqlDataReader reader = cmd.ExecuteReader())
{
Address address = new Address();
if (reader.Read())
{
address.AddressID = int.Parse(reader["AddressID"].ToString());
address.AddressLine = reader["AddressLine1"].ToString();
address.City = reader["City"].ToString();
address.StateProvince = reader["StateProvince"].ToString();
address.CountryRegion = reader["CountryRegion"].ToString();
address.PostalCode = reader["PostalCode"].ToString();
address.ModifiedDate = DateTime.Parse(reader["ModifiedDate"].ToString());
}
this.AddressIDTXT.Text = address.AddressID.ToString();
this.AddressTXT.Text = address.AddressLine;
this.CityTXT.Text = address.City;
this.StateProvinceTXT.Text = address.StateProvince;
this.CountryRegionTXT.Text = address.CountryRegion;
this.PostalTXT.Text = address.PostalCode;
this.ModifiedDateTXT.Text = address.ModifiedDate.ToShortDateString();
}
}
}
}
#endregion