读书人

在WinForm中导入数据后的数据操作和显

发布时间: 2012-12-28 10:29:04 作者: rapoo

在WinForm中导入数据后的数据操作和显示问题
自己学着做了个简单的数据管理程序,目前界面如下:
在WinForm中导入数据后的数据操作和显示有关问题

现在的问题有几个:
1、在dataGridView中“婚否”列显示的布尔值true,false变成 是,否。我不知道应该把IF判断替换语句具体放在哪里...还有一种方法是在“列编辑”中把这列变成Template列并编辑,但是我几乎把每个选项都点开了,实在是没找到“列编辑”选项中中转变Template的,只有变成CheckBox,Button等等,求教是我的版本问题,还是我压根就没找对地方...
2、“年龄”列在数据库里设的是int,我想在更新或者插入时在文本中限定输入数字。目前两种想法,一个是直接在文本输入时判定,问题是我还是找不到在哪个位置才能让它正确发挥作用..,第二个就是在按钮按下时用正则判断输入文本中的字符串,可是我是判断没有字母或者其它符号还是判断只有数字,感觉都不太好实现,求教..
3、当dataGridView中的数据被选定时,想要实现直接把数据读入下面的各个文本框中,因为我的更新语句有点问题,一片空白时点“更新”会把数据刷空,所以...
4、更新语句执行完毕后,会刷新界面,想要实现刷新之后依然定位于原来操作的列,想法是在刷新之前存储列的值,在之后读取,依然是语句用法把握不好...

以上的问题我都在网上找了一些解决的方法,但估计是因为本人基础有点差,所以都不能太好的运用并达到我想要的效果,包括自己的代码也是半抄半改出来的,所以在这里把问题总结一下发出来,也非常希望能得到大家的帮助!我自己的代码会贴在下面:

PS:如果可能的话,解决问题时最好(真不是伸手党,呜呜)能有代码加一些简单的说明,因为我刚学C#不久,有代码可能理解起来更直观一点,谢谢!

下面是代码:里面的n是用来提示操作成功失败的,我把相关的语句删掉了,不浪费大家时间,对这里能作一些什么修改的尽管吐糟,绝对不要手下留情!


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Text.RegularExpressions;

namespace WinFrom数据操作
{
public partial class frmManager : Form
{
public frmManager()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e) //查看,感觉好像没什么实际作用..
{
string sql = "select * from DB1";
SqlConnection conn = new SqlConnection(@"server=.;uid=user1;pwd=111;database=use");
SqlCommand cmd = new SqlCommand(sql, conn);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
}

private void button2_Click(object sender, EventArgs e) //插入,关于年龄的判断语句加在这里比较好吗?
{
int n = 0;
string sql = "insert into DB1(编号,姓名,年龄,婚否,入职时间,工资,好友,利率,职位,备注) values (@编号,@姓名,@年龄,@婚否,@入职时间,@工资,@好友,@利率,@职位,@备注)";
if (textBox2.Text.Trim() == "")
{
MessageBox.Show("编号不能为空!");


return;
}

SqlParameter[] param ={
new SqlParameter("@编号",Convert.ToInt16(textBox2.Text)),
new SqlParameter("@姓名",textBox1.Text),
new SqlParameter("@年龄",Convert.ToInt16(textBox3.Text)),
new SqlParameter("@婚否",Convert.ToBoolean(textBox4.Text)),
new SqlParameter("@入职时间",Convert.ToDateTime(textBox5.Text)),
new SqlParameter("@工资",Convert.ToDecimal(textBox6.Text)),
new SqlParameter("@好友",textBox7.Text),
new SqlParameter("@利率",Convert.ToDouble(textBox8.Text)),
new SqlParameter("@职位",textBox9.Text),
new SqlParameter("@备注",textBox10.Text)
};
SqlConnection conn = new SqlConnection(@"server=.;uid=user1;pwd=111;database=use");
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
cmd.Parameters.AddRange(param);
n = cmd.ExecuteNonQuery();


conn.Close();
Refresh();
}

public override void Refresh() //半抄半写的刷新重载类,和插入基本一样的.
{
string sql = "select * from DB1";
SqlConnection conn = new SqlConnection(@"server=.;uid=user1;pwd=111;database=use");
SqlCommand cmd = new SqlCommand(sql, conn);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);

dataGridView1.DataSource = dt;
}


private void frmManager_Load(object sender, EventArgs e) //初始化,还是重复语句.
{
string sql = "select * from DB1";
SqlConnection conn = new SqlConnection(@"server=.;uid=user1;pwd=111;database=use");
SqlCommand cmd = new SqlCommand(sql, conn);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);
dataGridView1.DataSource = dt;
}

private void button3_Click(object sender, EventArgs e) //删除,没什么好说的
{
string sql = "delete from DB1 where 1=1";
if (dataGridView1.CurrentRow.Selected)
{
sql = sql + " and 编号=" + Convert.ToInt32(dataGridView1.CurrentRow.Cells[0].Value.ToString());
}
int n = 0;
SqlConnection conn = new SqlConnection(@"server=.;uid=user1;pwd=111;database=use");


SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
n = cmd.ExecuteNonQuery();
conn.Close();
Refresh();
}

private void button4_Click(object sender, EventArgs e) //更新,请不要吐糟这里的格式什么的...
{

string sqlUpdate = "update DB1 set 姓名 ='" + textBox1.Text + "',年龄 ='" + textBox3.Text +
"',婚否 ='" + textBox4.Text + "',入职时间 ='" + textBox5.Text + "',工资 ='" + textBox6.Text + "',好友 ='" + textBox7.Text +
"',利率 ='" + textBox8.Text + "',职位 ='" + textBox9.Text + "',备注 ='" +
textBox10.Text+"'where 编号="+dataGridView1.CurrentRow.Cells[0].Value.ToString();
SqlConnection conn = new SqlConnection(@"server=.;uid=user1;pwd=111;database=use");
SqlCommand cmdUpdate = new SqlCommand(sqlUpdate, conn);
conn.Open();
int n = cmdUpdate.ExecuteNonQuery();
int m = dataGridView1.CurrentCell.RowIndex;
conn.Close();
Refresh();

}

private void textBox3_KeyPress(object sender, KeyPressEventArgs e) //想用作判断数字输入的,但是在这里打酱油.
{
if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && e.KeyChar != 8)
{
e.Handled = true;
}
}

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
/* 其实这个类我不太懂它存在的意义,如果可以也讲解下,谢谢了~ */


{
textBox1.Text = dataGridView1.Rows[e.RowIndex].Cells["姓名"].Value.ToString();
textBox2.Text = dataGridView1.Rows[e.RowIndex].Cells["编号"].Value.ToString();
textBox3.Text = dataGridView1.Rows[e.RowIndex].Cells["年龄"].Value.ToString();
textBox4.Text = dataGridView1.Rows[e.RowIndex].Cells["婚否"].Value.ToString();
textBox6.Text = dataGridView1.Rows[e.RowIndex].Cells["工资"].Value.ToString();
textBox7.Text = dataGridView1.Rows[e.RowIndex].Cells["好友"].Value.ToString();
textBox8.Text = dataGridView1.Rows[e.RowIndex].Cells["利率"].Value.ToString();
textBox9.Text = dataGridView1.Rows[e.RowIndex].Cells["职位"].Value.ToString();
textBox10.Text = dataGridView1.Rows[e.RowIndex].Cells["备注"].Value.ToString();

DateTime datetoDay = new DateTime().Date;
datetoDay = Convert.ToDateTime(dataGridView1.Rows[e.RowIndex].Cells["入职时间"].Value.ToString());
textBox5.Text = datetoDay.ToShortDateString();
}
}
}


[解决办法]

//只能输入数字
private DataGridViewTextBoxEditingControl EditingControl3;
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (dataGridView1.CurrentCellAddress.X == 2)
{
EditingControl3 = (DataGridViewTextBoxEditingControl)e.Control;
EditingControl3.SelectAll();
EditingControl3.KeyPress += new KeyPressEventHandler(EditingControl3_KeyPress);
}
}
private void EditingControl3_KeyPress(object sender, KeyPressEventArgs e)
{
if (dataGridView1.CurrentCellAddress.X == 2)
{
if (!(Char.IsNumber(e.KeyChar)


[解决办法]
e.KeyChar == '\b'))
{
e.Handled = true;
}
}
}


[解决办法]
问题1:可以将婚否列定义为combox列(可以自定义DataGridView列格式),然后根据数据库中的字段值来动态设置combox的显示值,代码如下:

/// <summary>
/// 设置DataGridView列
/// </summary>
private void SetDataGridViewStyle()
{
//这里为DataGridView添加了一个combox列
//依然绑定数据库中对应的列
DataGridViewComboBoxColumn column = new DataGridViewComboBoxColumn();
column.Name = "Marry";
column.DataPropertyName = "Marry";//对应数据库中的字段名
column.HeaderText = "婚否";
column.Width = 80;
this.dataGridView1.Columns.Add(column);
column.DataSource = GetData(); //这里需要设置一下combox的itemsource,以便combox根据数据库中对应的值自动显示信息
column.DisplayMember = "MarryStatus";//设置combox绑定显示信息(是、否)
column.ValueMember = "Marry"; //设置combox绑定显示信息(1,0即是true、false)
}

/// <summary>
/// 获得Combox的填充资源信息
/// </summary>
/// <returns></returns>
private DataTable GetData()
{
string sql = "select distinct Marry,case when Marry=1 then '是' else '否' end MarryStatus from DB1";
DataTable dt = PubData.GetData(sql);

return dt;
}


2:问题二textbox的keypress,你选择的事件里面更改下:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
//处理0-9、退格键


if (e.KeyChar == (char)0x08
[解决办法]
(e.KeyChar>='0'&&e.KeyChar<='9'))
e.Handled = false;
else
e.Handled = true;
}



3:问题三,直接对选择的datagridview行赋值给下面的textbox即可

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (this.dataGridView1.DataSource == null && this.dataGridView1.Rows.Count <= 0)
return;

txt_BookName.Text = this.dataGridView1.CurrentRow.Cells["BookName"] == null ? "" : this.dataGridView1.CurrentRow.Cells["BookName"].Value.ToString();//选择你自己的列名称即可
txt_Author.Text = this.dataGridView1.CurrentRow.Cells["Author"] == null ? "" : this.dataGridView1.CurrentRow.Cells["Author"].Value.ToString();
txt_Press.Text = this.dataGridView1.CurrentRow.Cells["Press"] == null ? "" : this.dataGridView1.CurrentRow.Cells["Press"].Value.ToString();
txt_Qty.Text = this.dataGridView1.CurrentRow.Cells["Qty"] == null ? "" : this.dataGridView1.CurrentRow.Cells["Qty"].Value.ToString();
}


4:问题四,定位对你更新的行,以及相应的列名称,让该单元格选中即可

//
int index = 1;//这里去你更新的行索引即可
this.dataGridView1.Rows[index].Cells["TagColumnName"].Selected = true;//指定的列

[解决办法]
第一个问题解决方法:
if (ds != null && ds.Tables.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
dataGridView1.Rows.Add();
dataGridView1["编号", i].Value = ds.Tables[0].Rows[i]["ID"].ToString();
dataGridView1["姓名", i].Value = ds.Tables[0].Rows[i]["表字段"].ToString();
dataGridView1["年龄", i].Value = ds.Tables[0].Rows[i]["表字段"].ToString();


dataGridView1["婚否", i].Value = ds.Tables[0].Rows[i]["表字段"].ToString()=="True"?"是":"否";



第二个问题解决方法
用textchange方法
在方法里面规定,如果超过范围则提示

正则:Regex.IsMatch(this.textbox.text.trim(),"~[0,100]$")方法
相关知识查看regex的相关内容

第三个问题解决方法

textBox1.Text = this.dataGridView1.CurrentRow.Cells["BookName"] == null ? "" : this.dataGridView1.CurrentRow.Cells["编号"].Value.ToString();

下面几个同理

在此之前最好把text clear()一下


在更新datagrilview之前对其clear()一下
第四个:
没有必要用
 public override void Refresh() //半抄半写的刷新重载类,和插入基本一样的.
{
string sql = "select * from DB1";
SqlConnection conn = new SqlConnection(@"server=.;uid=user1;pwd=111;database=use");
SqlCommand cmd = new SqlCommand(sql, conn);
DataTable dt = new DataTable();
SqlDataAdapter sda = new SqlDataAdapter(cmd);
sda.Fill(dt);

dataGridView1.DataSource = dt;
}


直接把 Refresh();改成button1_Click() ;


刷新之前存储列的值

你先定义几个string
然后把DataGridView的内容放在里面
比如
name=this.dataGridView1.CurrentRow.Cells["BookName"].value.tostring();

然后加进去在用相反的方法

读书人网 >C#

热点推荐