.NET-6.WinForm1.学习经验总结
目录
一、WinForm
学就完事!!!
GUI库:guna.UI、devexpress、CxFlatUI、Guna.UI2、MaterialWinforms
//推荐项目:
https://github.com/HuJinguang/CxFlatUI
https://github.com/yuzhengyang/Fork
https://github.com/lstratman/EasyTabs
https://github.com/YuanJianTing/WinForm.UI
https://github.com/Callumgm/Clean-GUI-Template
https://github.com/IgnaceMaes/MaterialSkin
https://github.com/Live-Charts/Live-Charts
https://github.com/kwwwvagaa/NetWinformControl
https://github.com/AshishKilmist/MetroFramework(推荐好看)
//自定义控件
https://blog.csdn.net/weixin_44634727/article/details/109139634
https://blog.csdn.net/kwwwvagaa/article/details/100586547
//C#:WinForm中使用IrisSkin4美化窗口界面(必须是.netframework)
https://blog.csdn.net/qq_43884946/article/details/125311115?
二、经验
1.输入文本框的验证
1.实现中文符号不能输入
/// <summary>
/// 输入验证
/// </summary>
/// <param name="e"></param>
public void check(KeyPressEventArgs e)
{
//实现中文符号不能输入
char[] charstr = { '!', '@', '#', '¥', '%', '&', '*', '(', ')', '《', '<', '>', '?', ':', '"', '{', '}', '~', '-', '[', ']', '|' };// 非法字符数组(有几个就写几个用单引号引上‘’用,点隔开)
for (int i = 0; i < charstr.Length; i++)
{
if (e.KeyChar == charstr[i])
//使用e.handled = true 禁止输入
e.Handled = true;
}
}
check(e);//调用
2.实现不重复数字输入
//只能输入数字和回车键,对于不符合条件的输入 使用e.handled = true 禁止输入
if (!Char.IsNumber(e.KeyChar) && e.KeyChar != (char)Keys.Back) e.Handled = true;
//判断是否为数字,为数字的话检查是否有重复数字,禁止重复输入
if (Char.IsNumber(e.KeyChar))
{
var no = this.txtAjdjhGH.Text;
if (no.Contains(e.KeyChar))
e.Handled = true;
}
2.全选
private void btnGtAll_Click(object sender, EventArgs e)
{
if (this.checkSelectAll.Checked == true)
{
string value = "true";
foreach (DataGridViewRow row in dgvList.Rows)
row.Cells[0].Value = value;
}
else
{
string value = "false";
foreach (DataGridViewRow row in dgvList.Rows)
row.Cells[0].Value = value;
}
//SetAllRowCheck(dgvList, ok);
}
3.按钮是否可操作
private void MakeButtonEnabledOrNot()
{
bool flag = (this.dgvList.Rows.Count == 0 ? false : true);
//this.btnBatchGrounding.Enabled = flag;
this.btnExport.Enabled = flag;
this.btnReset.Enabled = flag;
}
4.自动序号列
private void dgvList_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
//自动序号列 与数据无关
Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, this.dgvList.RowHeadersWidth - 4, e.RowBounds.Height);
TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), this.dgvList.RowHeadersDefaultCellStyle.Font, rectangle,
this.dgvList.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
}
5.获取控件
用this.dataGridView1.CurrentRow.Cells[0].Value获得id
listBox1.DisplayMember = ds.Tables[0].Columns[0].ToString();
listBox1.DisplayMember = dt.Columns[0].ToStiring();
foreach (Control ctr in panel2.Controls)
{
if (ctr is CheckBox)
{
CheckBox ck = ctr as CheckBox;
if (ck.Checked)
MessageBox.Show(ck.Text);
}
}
6.学习加载时
#region 窗体加载后的初始化
private void GHGroundingForm_Load(object sender, EventArgs e)
{
dtstartZD.Value = DateTime.Today.Date;
dtendZD.Value = DateTime.Today.Date;
dtstartPZ.Value = DateTime.Today.Date;
dtendPZ.Value = DateTime.Today.Date;
dgvList.AutoGenerateColumns = false; // 不允许 datagridview 自动产生列
dgvList.ReadOnly = true;
//记录DataGridView设置文本居中显示
dgvList.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
this.btnBatchGrounding.Enabled = false;
dgvList.Columns[19].Visible = false;
MakeButtonEnabledOrNot();
Query();
}
//创建窗口句柄时出错
while (tabPage.Controls.Count > 0)
{
Control ct = tabPage.Controls[0];
tabPage.Controls.Remove(ct);
ct.Dispose();
ct = null;
}
#endregion
7.实现拖拽
private int tmpx=0, tmpy=0;
private bool MoveFlag;
private void button1_MouseUp(object sender, MouseEventArgs e)
MoveFlag = false;
private void button1_MouseMove(object sender, MouseEventArgs e)
{
if (MoveFlag)
{
button1.Left += Convert.ToInt16(e.X -this.tmpx );//设置x坐标.
button1.Top += Convert.ToInt16(e.Y - this.tmpy);//设置y坐标.
}
}
private void button1_MouseDown(object sender, MouseEventArgs e)
{
MoveFlag = true;
this.tmpx = e.X;
this.tmpy = e.Y;
}
>第二种方法,使用自定义控件
private int ox, oy;
public UserControlLine()
{
InitializeComponent();
MouseDown += new MouseEventHandler(UserControlLine_MouseDown);
MouseMove += new MouseEventHandler(UserControlLine_MouseMove);
}
private void UserControlLine_MouseDown(object? sender, MouseEventArgs e)
{
ox=e.X;
oy = e.Y;
BringToFront();
}
private void UserControlLine_MouseMove(object? sender, MouseEventArgs e)
{
var el = (Control)sender;
if (e.Button == MouseButtons.Left)
{
el.Top += e.Y - oy;
el.Left += e.X - ox;
Parent.Invalidate();
}
}
#endregion
8.自定义控件
// </summary>
private string[] btns;
/// <summary>
/// 需要显示的按钮文字
/// </summary>
/// <value>The BTNS.</value>
[Description("需要显示的按钮文字"), Category("自定义")]
public string[] Btns
{
get { return btns; }
set { btns = value; }
}
>
/// <summary>
/// 控件的背景色
/// </summary>
private Color _backColorUC = Color.Transparent; //声明一个颜色变量 透明色 用于初始化 控件背景色
private Color m_tipsColor = Color.FromArgb(232, 30, 99);
[Description("控件的背景色"), Category("自定义")] //新建控件说明 用来描述控件的作用;一个类别.
public Color BackColorUC //创建一个属性名 用于在属性窗口中显示出来
{
get { return _backColorUC; } //返回 颜色变量 初始化背景色 为透明
set //set 是当用户在属性窗口设置颜色的时候执行
{
_backColorUC = value; //获取用户在属性窗口中 选择的颜色 赋值给这个颜色变量
this.BackColor = _backColorUC; //将颜色赋值给 控件的背景颜色
Refresh();//强制控件使其工作区无效,并立即重绘自己和任何子控件。
}
}
private Color _backcolorMove = Color.Transparent;
[Description("光标移动到控件上方显示的颜色")]
public Color backcolorMove //再创建一个属性 用于接受 用户希望鼠标移动到 控件上时显示的颜色
{
get { return _backcolorMove; }
set { _backcolorMove = value; } //获取颜色 先不赋值
}
private void button1_MouseMove(object sender, MouseEventArgs e)
{
if (_backcolorMove != Color.Transparent) // 如果 用户在属性窗口为backcolorMove设置了颜色 _backColorUC 就不是原始的 透明色了 此时
{
BackColorUC = _backcolorMove; //将用户设置的值赋值给BackColorUC 让它先赋值给_backColorUC再赋值给this.BackColor设置颜色
}
}
public event EventHandler? ButtontestClick;
private void button1_Click(object sender, EventArgs e)
{
ButtontestClick?.Invoke(sender, e);
}
#endregion
winform 连接mysql
- 下载nuget包 MySql.Data
- 建立一个公共类 mysqlConnection.cs
- 建立一个窗体Main.Form.cs
- 这个其实也是ado.net 数据访问技术,值得参考
//mysqlConnection.cs
public class mysqlConnection
{
public MySqlConnection mySqlCont { get; set; }
//hostaddress= "192.168.2.8"
//hostaddress= "192.168.43.85"
public mysqlConnection(string hostaddress= "localhost", string databaseName="traytest",string name="root",string password="123456")
{
string connetStr = "server=" + hostaddress + ";User Id=" + name + ";password=" + password + ";database=" + databaseName; //localhost不支持ssl连接时,最后一句一定要加!!!
mySqlCont = new MySqlConnection(connetStr);
try
{
mySqlCont.Open(); //连接数据库
MessageBox.Show("数据库连接成功", "提示", MessageBoxButtons.OK);
Console.WriteLine("成功");
//mysqlConnection.mySqlCont.Close(); //断开连接
//MessageBox.Show("数据库关闭成功", "提示", MessageBoxButtons.OK);
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK); //显示错误信息
Console.WriteLine("失败。");
}
}
}
//MainForm.cs
public partial class MainForm : Form
{
public mysqlConnection mysqlConnection;
MySqlCommand SQLCmd;
public int s1;
public string s2, s3;
public MainForm()
{
InitializeComponent();
mysqlConnection = new mysqlConnection();
query_Click();
}
private void MainForm_Load(object sender, EventArgs e)
{
dataGridView1.Rows[0].Selected = true;
}
private void query_Click()
{
string searchStr = "select * from user";
MySqlDataAdapter adapter = new MySqlDataAdapter(searchStr, mysqlConnection.mySqlCont);
DataSet dataSet = new DataSet();
adapter.Fill(dataSet, "table1");
this.dataGridView1.DataSource = dataSet.Tables["table1"];
dataGridView1.Rows[0].Selected = true;
}
private void bt_ADD_Click(object sender, EventArgs e)
{
s1 = Convert.ToInt16(textBox1.Text);
s2 = textBox2.Text;
s3 = textBox3.Text;
try
{
string searchStr = "insert into user values(" + s1 + ",'" + s2 + "','" + s3 + "')";
SQLCmd = new MySqlCommand(searchStr, mysqlConnection.mySqlCont);
SQLCmd.ExecuteNonQuery();
MessageBox.Show("插入成功", "提示", MessageBoxButtons.OK);
//bt_CONNECT_Click(sender, e);
query_Click();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK);
}
}
//删除
private void bt_DELETE_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim() != "")
{
try
{
s1 = Convert.ToInt16(textBox1.Text);
string searchStr = ("delete from user where id=" + s1);
SQLCmd = new MySqlCommand(searchStr, mysqlConnection.mySqlCont);
SQLCmd.ExecuteNonQuery();
MessageBox.Show("删除成功!", "提示", MessageBoxButtons.OK);
//bt_CONNECT_Click(sender, e);
query_Click();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK);
}
}
else
{
try
{
for (int i = 0; i < 100; i++)//遍历所有选中的行
{
if (dataGridView1.Rows[i].Selected == true)
{
string value = dataGridView1.Rows[i].Cells[0].Value.ToString();
int tmp = Convert.ToInt32(value);
string sql = ("delete from user where id=" + tmp);
SQLCmd = new MySqlCommand(sql, mysqlConnection.mySqlCont);
SQLCmd.ExecuteNonQuery();
MessageBox.Show("删除成功!", "提示", MessageBoxButtons.OK);
//bt_CONNECT_Click(sender, e);
query_Click();
break;
}
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK);
}
}
}
//修改
private void bt_MODIFY_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim() != "")
{
s1 = Convert.ToInt16(textBox1.Text);
try
{
string searchStr = ($"update user set name='{textBox2.Text.Trim()}',age='{textBox3.Text.Trim()}' where id=" + s1);
SQLCmd = new MySqlCommand(searchStr, mysqlConnection.mySqlCont);
SQLCmd.ExecuteNonQuery();
// bt_CONNECT_Click(sender, e);
query_Click();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK);
}
}
else
{
try
{
for (int i = 0; i < 100; i++)//遍历所有选中的行
{
if (dataGridView1.Rows[i].Selected == true)
{
string value = dataGridView1.Rows[i].Cells[0].Value.ToString();
string name = dataGridView1.Rows[i].Cells[1].Value.ToString();
string age = dataGridView1.Rows[i].Cells[2].Value.ToString();
int tmp = Convert.ToInt32(value);
string searchStr = ($"update user set name='{name}' ,age='{age}' where id=" + tmp);
SQLCmd = new MySqlCommand(searchStr, mysqlConnection.mySqlCont);
SQLCmd.ExecuteNonQuery();
MessageBox.Show("修改成功!", "提示", MessageBoxButtons.OK);
//bt_CONNECT_Click(sender, e);
query_Click();
break;
}
}
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK);
}
}
}
}
总结
前赴后继