在datagridview单元格中输入字符串 按下tab光标移到下一单元格 此时自动判断该字符串是否存在于sql数据库中,存在则messagebox show XXXX已存在,若不存在,无任何操作
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;
namespace Q692913
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Columns.Add("id", "NO.");
dataGridView1.Columns.Add("name", "姓名");
DataClasses1DataContext db = new DataClasses1DataContext();
foreach (var item in db.Table1s)
{
dataGridView1.Rows.Add(new object[] { item.id, item.name });
}
dataGridView1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CellEndEdit);
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1)
{
DataClasses1DataContext db = new DataClasses1DataContext();
string name = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
if (db.Table1s.Any(x => x.name == name))
{
MessageBox.Show(name + " 已经存在!");
}
}
}
}
}
这里可以采用鼠标离开事件onblur 然后利用ajax请求数据库返回对应状态或数据。希望采纳。
一楼的答案看似实现了你的功能,但是并不是最理想的方案,你需要的是处理Tab键消息,实现你想要的功能,一楼在EndEdit事件中处理当然是不理想的,因为当你在编辑某个单元格的时候,编辑完成按下Tab键后那么会先自动结束编辑状态,所以一楼投机取巧的在EndEdit方法中来处理会是怎么样的呢?两种情况,一:数据库中已经存在这个字符串,那么弹出你需要的提示消息,然后再处理Tab键消息,跳转到下一个单元格,显然这不是你想要的,你想要的是停留在当前单元格的编辑状态,重新编辑这个单元格的值。二:数据库中不存在相同的字符串值,那么跳转到下一个单元格。最好的处理方法当然是重写ProcessCmdKey 方法,然后自己处理Tab键消息。至于判断据库中是否有相同的字符串,你直接用sql查询命令查询就可以了,或者用专门操作sql的库去操作,网络上很多相关的控件或者库,很方便,在这里给你贴一个简单的操作sql操作代码参考一下
public class DBHelper
{
SqlConnection con = null;
public DBHelper()
{
con = CreateConnection();
con.Open();
}
/// <summary>
/// 创建数据库连接
/// </summary>
/// <returns></returns>
public SqlConnection CreateConnection()
{
//这里链接数据库的字符串换成你自己实际的字符串链接字符串
SqlConnection con = new SqlConnection("Data Source=.;Database=Kb.Data;Integrated Security=SSPI;");
return con;
}
/// 最常用的是用下面的语句,实际运用中需要根据需要修改语句,比如要考虑执行效率等问题,还可以用 select isnull((select top(1) 1 from tableName where 查询条件), 0)
/// if exists (select * from tableName where 查询条件) select '1' else select '0'
/// <summary>
/// 判断某字段的值是否存在于数据库中
/// </summary>
/// <param name="TableName">查询的表名</param>
/// <param name="KeyName">字段名</param>
/// <param name="KeyValue">字段值</param>
/// <returns></returns>
public bool IsValueExists(string TableName, string KeyName, string KeyValue)
{
if (string.IsNullOrEmpty(KeyName) == true || string.IsNullOrEmpty(KeyValue) == true)
return false;
string sql = "SELECT COUNT(*) FROM " + TableName + " WHERE " + KeyName + "='" + KeyValue + "'";
SqlCommand cmd = new SqlCommand(sql, con);
int count = Convert.ToInt32(cmd.ExecuteScalar());
return count > 0 ? true : false;
}
public DataTable SearchValue(string TableName, string KeyName = "", string KeyValue = "")
{
string sql = "SELECT id,number,name FROM " + TableName + " WHERE 1=1";
if (string.IsNullOrEmpty(KeyName) == false && string.IsNullOrEmpty(KeyValue) == false)
sql = " AND " + KeyName + "=" + KeyValue;
SqlCommand cmd = new SqlCommand(sql, con);
DataTable table = new DataTable(TableName);
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(table);
return table;
}
}
重写ProcessCmdKey方法处理Tab消息
protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == Keys.Tab)
{
if (dataGridView1.IsCurrentCellInEditMode)
{
int irows = dataGridView1.CurrentCell.RowIndex;
int icols = dataGridView1.CurrentCell.ColumnIndex;
if (irows > -1 && icols > -1)
{
dataGridView1.EndEdit();
//从数据库中查询数据是否存在
string value = dataGridView1.Rows[irows].Cells[icols].Value.ToString();
DBHelper db = new DBHelper();
if (db.IsValueExists("dbo.UserInfo", dataGridView1.Columns[icols].DataPropertyName, value))
{
MessageBox.Show(value + " 已存在");
dataGridView1.BeginEdit(true);
return true;
}
else
{
SendKeys.Send("{Tab}");
return base.ProcessCmdKey(ref msg, keyData);
}
}
}
}
return base.ProcessCmdKey(ref msg, keyData);
}
当然了,你如果想要获取焦点的同时进入编辑状态,就是按下Tab键,跳转到下一个单元格,自动进入编辑状态,就是移动光标的效果,那么加一个CellEnter事件就好了
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
dataGridView1.BeginEdit(true);
}
在这里声明一下,我只是看到楼主的问题还没解决,纯粹想帮楼主而已,楼主如果还能看到这些回复,我建议你采纳一楼的意见,毕竟他是第一个出来给你认真回答问题的,而且还是很用心的给你写了代码,虽然没有完美解决你的问题,但是说句实在话,凡是第一个认真回答问题,而且只要不是错误的答案,都应该得到奖励,你采纳楼主的建议之后我会详细给你分析这个问题,而且把实例代码发给你,按照你的要求肯定是要处理Tab消息的,当然你不用Tab键,用鼠标操作的时候也是要处理的,不然的话都不能够说完整实现了你想要的功能完整代码你可以留下邮箱,给你发过去
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace Q692913
{
public partial class Form1 : Form
{
private string connstr = "Data Source=.\\sqlexpress;Initial Catalog=Q692913DB;Integrated Security=True;Pooling=False";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.Columns.Add("id", "NO.");
dataGridView1.Columns.Add("name", "姓名");
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
SqlCommand cmd = new SqlCommand("select * from table1", conn);
var reader = cmd.ExecuteReader();
while (reader.Read())
{
dataGridView1.Rows.Add(new object[] { reader["id"].ToString(), reader["name"].ToString() });
}
reader.Close();
conn.Close();
dataGridView1.CellEndEdit += new DataGridViewCellEventHandler(dataGridView1_CellEndEdit);
}
private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
if (e.ColumnIndex == 1)
{
SqlConnection conn = new SqlConnection(connstr);
conn.Open();
string name = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
SqlCommand cmd = new SqlCommand("select count(*) from table1 where name=N'" + name + "'", conn);
int count = (int)cmd.ExecuteScalar();
if (count > 0)
{
MessageBox.Show(name + " 已经存在!");
}
}
}
}
}