I'm trying to get an input as text and save it to SQL table,
the code works fine if the string isn't too long, but when you exceed from about 70 characters the SaveChanges(); command isn't able to save the data.
SQL data type is set to nvarchar(max). Any idea?
private void btnSave_Click(object sender, EventArgs e)
{
Model.TBL_USERS USR = new Model.TBL_USERS();
USR.USR_NAME = txtNAME.Text;
USR.USR_LAST = txtLAST.Text;
USR.USR_MOBILE = txtMOBILE.Text;
USR.USR_TEL1 = txtTEL1.Text ;
USR.USR_ADDRESS = txtADDRESS.Text;
USR.USR_COMPANY = txtCOMPANY.Text;
//USR.USR_COMPANY = "=chrome..69i57.13150j0j4&sourceid=chrome&ie=UTF-8";
DB.TBL_USERS.Add(USR);
DB.SaveChanges();
dataGridView1.DataSource = "";
dataGridView1.DataSource = DB.TBL_USERS.ToList();
}
this is the whole code in the solution :
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Model.SAMA_User_CRM_V1 DB = new Model.SAMA_User_CRM_V1();
int IDGRID;
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.DataSource = DB.TBL_USERS.ToList();
}
private void btnSave_Click(object sender, EventArgs e)
{
Model.TBL_USERS USR = new Model.TBL_USERS();
USR.USR_NAME = txtNAME.Text;
USR.USR_LAST = txtLAST.Text;
USR.USR_MOBILE = txtMOBILE.Text;
USR.USR_TEL1 = txtTEL1.Text ;
USR.USR_ADDRESS = txtADDRESS.Text;
USR.USR_COMPANY = txtCOMPANY.Text;
//USR.USR_COMPANY = "=chrome..69i57.13150j0j4&sourceid=chrome&ie=UTF-8";
DB.TBL_USERS.Add(USR);
DB.SaveChanges();
dataGridView1.DataSource = "";
dataGridView1.DataSource = DB.TBL_USERS.ToList();
}
private void btnDELETE_Click(object sender, EventArgs e)
{
var qdel = DB.TBL_USERS.Where(x => x.ID == IDGRID).ToList();
foreach (var item in qdel)
{
DB.TBL_USERS.Remove(item);
}
DB.SaveChanges();
dataGridView1.DataSource = "";
dataGridView1.DataSource = DB.TBL_USERS.ToList();
}
private void dataGridView1_RowEnter(object sender, DataGridViewCellEventArgs e)
{
IDGRID = (int)dataGridView1.Rows[e.RowIndex].Cells["ID"].Value;
}
}
}
considering the comments i found out where the problem is :
initially the model was created with a SQL table that used nvarchar(50) and after changing that to nvarchar(500) or nvarchar(max) the model.edmx needed to be updated ... after updating the model all things worked like a charm .
Related
Can anyone help me on how can I do auto suggest on gridview when typing on textbox. Almost 1 week I seek for the solution. I already check my select statement, it connect to my database. And now I do not know why that coding is not function. Please somebody help me. This is my current code:
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.Drawing.Imaging;
using System.IO;
namespace EmployeeVerification
{
public partial class Form1 : Form
{
//Connection String
string cs = "Server=..;User Id=sa;Password=..;Database=..";
SqlConnection con;
SqlDataAdapter adapt;
DataTable dt;
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
//table to show in gridview
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("select [name], [empno], [workno] from [GMT].[dbo].[m_employee] where not [recsts] = 'R' order by empno", con);
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
//make the textbox read only
textBoxICPass.ReadOnly = true;
textBoxPassport.ReadOnly = true;
textBoxDept.ReadOnly = true;
textBoxSection.ReadOnly = true;
pictureBox1.Visible = false;
dataGridView1.Visible = false;
textBoxEmplNo.CharacterCasing = CharacterCasing.Upper;
textBoxWorkNo.CharacterCasing = CharacterCasing.Upper;
textBoxName.CharacterCasing = CharacterCasing.Upper;
DataGridViewColumn column = dataGridView1.Columns[0];
column.Width = 300;
}
//auto suggest on gridview when typing on textbox
private void textBoxName_TextChanged(object sender, EventArgs e)
{
con = new SqlConnection(cs);
con.Open();
adapt = new SqlDataAdapter("select [name], [empno], [workno] from m_employee where name like '%" + textBoxName.Text + "%' and not [recsts] = 'R' order by empno", con);
dt = new DataTable();
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
if (textBoxName.Text != null)
{
dataGridView1.Visible = true;
}
}
private void labelEmplNo_Click(object sender, EventArgs e)
{
}
private void textBoxEmplNo_TextChanged(object sender, EventArgs e)
{
}
private void textBoxWorkNo_TextChanged(object sender, EventArgs e)
{
}
private void labelTitle_Click(object sender, EventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void buttonSelect_Click(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void textBoxICPass_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
{
}
//show the row value in textbox
private void dataGridView1_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
textBoxName.Text = dataGridView1.SelectedRows[0].Cells[0].Value.ToString();
textBoxEmplNo.Text = dataGridView1.SelectedRows[0].Cells[1].Value.ToString();
textBoxWorkNo.Text = dataGridView1.SelectedRows[0].Cells[2].Value.ToString();
textBoxICPass.Text = dataGridView1.SelectedRows[0].Cells[3].Value.ToString();
textBoxPassport.Text = dataGridView1.SelectedRows[0].Cells[4].Value.ToString();
textBoxDept.Text = dataGridView1.SelectedRows[0].Cells[5].Value.ToString();
textBoxSection.Text = dataGridView1.SelectedRows[0].Cells[6].Value.ToString();
dataGridView1.Visible = false;
}
//clear all the textbox fields after click
private void buttonClear_Click(object sender, EventArgs e)
{
foreach (Control crt in this.Controls)
{
if (crt.GetType() == typeof(TextBox))
crt.Text = "";
pictureBox1.Visible = false;
}
dataGridView1.Visible = false;
}
private void labelICPass_Click(object sender, EventArgs e)
{
}
private void textBoxWorkNo_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (textBoxWorkNo.Text != "")
{
//Do something
string selectSql = "select name, empno, icnum, passport, deptno, section from m_employee where workno=#workno";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.Parameters.AddWithValue("#workno", textBoxWorkNo.Text);
bool isDataFound = false;
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
isDataFound = true;
textBoxEmplNo.Text = (read["empno"].ToString());
textBoxName.Text = (read["name"].ToString());
textBoxICPass.Text = (read["icnum"].ToString());
textBoxPassport.Text = (read["passport"].ToString());
textBoxDept.Text = (read["deptno"].ToString());
textBoxSection.Text = (read["section"].ToString());
}
}
if(!isDataFound)
{
textBoxEmplNo.Text = "";
textBoxWorkNo.Text = "";
textBoxName.Text = "";
// Display message here that no values found
MessageBox.Show("No Result Found");
}
}
finally
{
con.Close();
}
}
else
{
textBoxEmplNo.Text = "";
textBoxName.Text = "";
}
string imgFilePath = #"C:\Users\hamizah\Documents\Visual Studio 2013\WebSites\EV\photo\" + textBoxWorkNo.Text + ".jpg";
if (File.Exists(imgFilePath))
{
pictureBox1.Visible = true;
pictureBox1.Image = Image.FromFile(imgFilePath);
}
else
{
// Display message that No such image found
// MessageBox.Show("No Image Found");
pictureBox1.Visible = true;
pictureBox1.Image = Image.FromFile(#"C:\Users\hamizah\Documents\Visual Studio 2013\WebSites\EV\photo\No-image-found.jpg");
}
}
}
private void textBoxEmplNo_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
if (textBoxEmplNo.Text != "")
{
string selectSql = "select name, workno, icnum, passport, deptno, section from m_employee where empno=#empno";
SqlCommand cmd = new SqlCommand(selectSql, con);
cmd.Parameters.AddWithValue("#empno", textBoxEmplNo.Text);
bool isDataFound = false;
try
{
con.Open();
using (SqlDataReader read = cmd.ExecuteReader())
{
while (read.Read())
{
isDataFound = true;
textBoxWorkNo.Text = (read["workno"].ToString());
textBoxName.Text = (read["name"].ToString());
textBoxICPass.Text = (read["icnum"].ToString());
textBoxPassport.Text = (read["passport"].ToString());
textBoxDept.Text = (read["deptno"].ToString());
textBoxSection.Text = (read["section"].ToString());
}
}
if(!isDataFound)
{
textBoxEmplNo.Text = "";
textBoxWorkNo.Text = "";
textBoxName.Text = "";
// Display message here that no values found
MessageBox.Show("No Result Found");
}
}
finally
{
con.Close();
}
}
else
{
textBoxWorkNo.Text = "";
textBoxName.Text = "";
}
string imgFilePath = #"C:\Users\hamizah\Documents\Visual Studio 2013\WebSites\EV\photo\" + textBoxEmplNo.Text + ".jpg";
if(File.Exists(imgFilePath))
{
pictureBox1.Visible = true;
pictureBox1.Image = Image.FromFile(imgFilePath);
}
else
{
// Display message that No such image found
MessageBox.Show("No Image Found");
}
}
}
}
}
Make these changes within your code:
You are setting dataGridView1.Visible = false; at various places within your code, remove all of them for instance, just for the sake of testing, you can add them later based on your requirements.
Remove this part of query where not [recsts] = 'R' order by empno" because for now it is useless and I don't understand why you are using this, you can apply filters later and also select ... from m_employee instead of [dbo]... etc..
Instead of dataGridView1.SelectedRows[0].Cells[0].Value.ToString(); get data from selected row like this: textBoxName.Text = dataGridView1.Rows[e.RowIndex].Cells["name"].Value.ToString(); Because in future, if you increase/decrease the number of columns or re-arrange the order of getting data, it will not effect.
I've tested your code with these modifications and it works perfectly.
I created a gridview in asp.net which has two columns of DATETIME datatype, when I connected to mysql database to save it within, it shows me an error " Incorrect datetime value: '01/01/2017 00:07:26' for column 'LogInDate_Time' at row 1" in cmd.ExecuteNonQuery(); line
How to solve it?
C#
protected void Page_Load(object sender, EventArgs e)
{
}
protected void LoggedIn(object sender, EventArgs e)
{
CheckBox checkedCheckBox = (sender as CheckBox);
GridViewRow checkedRow = (checkedCheckBox.NamingContainer as GridViewRow);
Label loggedInDateTime = checkedRow.FindControl("lblLoggedInDateTime") as Label;
if (checkedCheckBox.Checked)
{
loggedInDateTime.Text = DateTime.Now.ToString();
}
else
{
loggedInDateTime.Text = "";
}
}
protected void LoggedOut(object sender, EventArgs e)
{
CheckBox checkedCheckBox = (sender as CheckBox);
GridViewRow checkedRow = (checkedCheckBox.NamingContainer as GridViewRow);
Label loggedOutDateTime = checkedRow.FindControl("lblLoggedOutDateTime") as Label;
if (checkedCheckBox.Checked)
{
loggedOutDateTime.Text = DateTime.Now.ToString();
}
else
{
loggedOutDateTime.Text = "";
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
string Attendance_ID = (row.FindControl("lblAttendanceID") as Label).Text;
string Attendance_Name = (row.FindControl("lblAttendanceName") as Label).Text;
string LogInDate_Time = (row.FindControl("lblLoggedInDateTime") as Label).Text;
string LogOutDate_Time = (row.FindControl("lblLoggedOutDateTime") as Label).Text;
InsertData(Attendance_ID, Attendance_Name, LogInDate_Time, LogOutDate_Time);
}
lblMessage.Text = "All Records Saved Successfully!!";
}
public void InsertData(string Attendance_ID, string Attendance_Name, string LogInDate_Time, string LogOutDate_Time)
{
//Your saving code.
string A = "server=localhost; userid=; password=; database=admindb; allowuservariables=True; Convert Zero Datetime=True; Allow Zero Datetime=True ";
using (MySqlConnection connection = new MySqlConnection(A))
{
string UpdateQuery = " INSERT INTO Attendance_Table (Attendance_ID, Attendance_Name,LogInDate_Time, LogOutDate_Time)" + " VALUES (#Attendance_ID,#Attendance_Name,#LogInDate_Time,#LogOutDate_Time)";
MySqlCommand cmd = new MySqlCommand(UpdateQuery, connection);
MySqlParameter paramAttendance_ID = new MySqlParameter("#Attendance_ID", Attendance_ID);
cmd.Parameters.Add(paramAttendance_ID);
MySqlParameter paramAttendance_Name = new MySqlParameter("#Attendance_Name", Attendance_Name);
cmd.Parameters.Add(paramAttendance_Name);
MySqlParameter paramLogInDate_Time = new MySqlParameter("#LogInDate_Time", LogInDate_Time);
cmd.Parameters.Add(paramLogInDate_Time);
MySqlParameter paramLogOutDate_Time = new MySqlParameter("#LogOutDate_Time", LogOutDate_Time);
cmd.Parameters.Add(paramLogOutDate_Time);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
protected void lbInsert_Click(object sender, EventArgs e)
{
ObjectDataSource1.InsertParameters["Attendance_ID"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtID")).Text;
ObjectDataSource1.InsertParameters["Attendance_Name"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("TxtName")).Text;
ObjectDataSource1.InsertParameters["Attendance_Con"].DefaultValue = ((CheckBox)GridView1.FooterRow.FindControl("cbAttendanceCon")).Text;
ObjectDataSource1.InsertParameters["LogInDate_Time"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtLogIn")).Text;
ObjectDataSource1.InsertParameters["Leaving_Con"].DefaultValue = ((CheckBox)GridView1.FooterRow.FindControl("cbLeavingCon")).Text;
ObjectDataSource1.InsertParameters["LogOutDate_Time"].DefaultValue = ((TextBox)GridView1.FooterRow.FindControl("txtLogOut")).Text;
ObjectDataSource1.Insert();
}
}
MySQL wants date in YYYY-MM-DD format.
Reference:
https://dev.mysql.com/doc/refman/5.5/en/datetime.html
We want to attach a combo box into a cell of data grid view. Now it works with mouse click. but for faster moving of form we need it to work using keyboard.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
void CreateGrid()
{
DataTable dt = new DataTable();
dt.Columns.Add("EmpName", typeof(string));//0
dt.Columns.Add("EmpID", typeof(int));//1
dt.Columns.Add("PhoneNo", typeof(string));//2
dt.Columns.Add("Address", typeof(string));//3
dt.Columns.Add("Email", typeof(string));//4
dataGridView1.DataSource = dt;
dataGridView1.Controls.Add(comboBox1); // Add System.Windows.Form.ComboBox in Datagridview
}
private void Form1_Load(object sender, EventArgs e)
{
CreateGrid();
fillRecords(1);
}
string SQL;
void fillRecords(int QueryNo)
{
SqlConnection con = new SqlConnection(#"Data Source=APPLE-PC\RNS;Initial Catalog=DemoDatabase;User ID=sa;Password=rns11");
con.Open();
if (QueryNo==1)
{
SQL = "Select EmpName,EmpID from EmployeeMaster";
}
else if (QueryNo==2)
{
SQL = "Select PhoneNo,Address from EmployeeMaster where EmpID=" + comboBox1.SelectedValue.ToString();
}
SqlDataAdapter da = new SqlDataAdapter(SQL, con);
DataTable dt = new DataTable();
da.Fill(dt);
con.Close();
if (QueryNo == 1)
{
comboBox1.DataSource = dt;
comboBox1.DisplayMember = "EmpName";
comboBox1.ValueMember = "EmpID";
}
else if (QueryNo == 2)
{
dataGridView1.CurrentRow.Cells[1].Value = comboBox1.SelectedValue.ToString();
dataGridView1.CurrentRow.Cells[0].Value = comboBox1.Text;
DataRow dr=dt.Rows[0];
dataGridView1.CurrentRow.Cells[2].Value = dr["PhoneNo"];
dataGridView1.CurrentRow.Cells[3].Value = dr["Address"];
}
}
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
//Visible Location on Current Cell
if (dataGridView1.CurrentCell.ColumnIndex==0)
{
comboBox1.Visible = true;
comboBox1.Location = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Location;
comboBox1.Size = dataGridView1.CurrentCell.Size;
}
}
private void dataGridView1_CellLeave(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex == 0)
{
comboBox1.Visible = false;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (comboBox1.SelectedValue.ToString()!="System.Data.DataRowView")
{
fillRecords(2);
}
}
}
this solution is given by Sinisa Hajnal.
It should work using keyboard, but usually need to press F2 first to enter edit mode. I can solve this by handling CellEnter event and opening edit mode for combobox and setting focus to it inside.
`
private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (dataGridView1.CurrentCell.ColumnIndex==0)
{
comboBox1.Visible = true;
comboBox1.Location = dataGridView1.GetCellDisplayRectangle(e.ColumnIndex, e.RowIndex, true).Location;
comboBox1.Size = dataGridView1.CurrentCell.Size;
comboBox1_SelectedIndexChanged(null, null);
comboBox1.Focus();//focus on Combobox
}
}
`
I just learn linq and trying to make insert update delete with linq and ado.net data entity model. Now I'm have some problem, when I'm insert some data, the datagridview not show that, I must close the program and run it again to show the latest data that I'm entry. Here the code :
namespace TesDB
{
public partial class Form1 : Form
{
private Database1Entities de = new Database1Entities();
int index;
public Form1()
{
InitializeComponent();
var query = from x in de.MsEmployees
select x;
dataGridView1.DataSource = query;
dataGridView1.Refresh();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void loadtext()
{
textBox1.Text = dataGridView1.Rows[index].Cells[0].Value.ToString();
textBox2.Text = dataGridView1.Rows[index].Cells[1].Value.ToString();
textBox3.Text = dataGridView1.Rows[index].Cells[2].Value.ToString();
}
private void button2_Click(object sender, EventArgs e)
{
string EmployeeID = dataGridView1.Rows[index].Cells[0].Value.ToString();
var employee = (from x in de.MsEmployees
where x.EmployeeID == EmployeeID
select x).First();
employee.EmployeeID = textBox1.Text;
employee.EmployeeName = textBox2.Text;
employee.Salary = int.Parse(textBox3.Text);
de.SaveChanges();
Refresh();
}
private void button3_Click(object sender, EventArgs e)
{
string EmployeeID = dataGridView1.Rows[index].Cells[0].Value.ToString();
// int id1 = int.Parse(EmployeeID);
var Employee = (from x in de.MsEmployees
where x.EmployeeID == EmployeeID
select x).First();
de.MsEmployees.DeleteObject(Employee);
de.SaveChanges();
Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
string employeeID = dataGridView1.Rows[index].Cells[0].Value.ToString();
var employee = (from x in de.MsEmployees
where x.EmployeeID == employeeID
select x.EmployeeID).First();
MsEmployee me = new MsEmployee();
me.EmployeeID = textBox1.Text;
me.EmployeeName = textBox2.Text;
me.Salary = int.Parse(textBox3.Text);
de.AddToMsEmployees(me);
de.SaveChanges();
this.Refresh();
}
private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
index = e.RowIndex;
loadtext();
}
}
}
`
I'm using refresh() that work for Update and Delete but it not work for insert does anyone know how to refresh that table when I'm done insert?
make a method of refresh() and paste ur Query inside and call it behind the button
public void refresh()
{
//Paste ur Query here and call it behind the button_click Event
}
Using Linq to sql through bindingsource control in WinForms, I could not get this to work:
private void textBox1_TextChanged(object sender, EventArgs e)
{
productBindingSource.Filter = string.Format("ProductName LIKE '*{0}*'", textBox1.Text);
MessageBox.Show("Changed");
}
NorthwindDataContext dc;
private void FrmFilter_Load(object sender, EventArgs e)
{
// create new data context
dc = new NorthwindDataContext();
// set the binding source data source to the full order table
var qry = (from p in dc.Products select p).ToList();
this.productBindingSource.DataSource = dc.GetTable<Product>();
}
When I type some letter in the textbox nothing happens in the datagridview.
Thanks for advices ...
Try changing your code to look like this:
NorthwindDataContext dc;
private void FrmFilter_Load(object sender, EventArgs e)
{
dc = new NorthwindDataContext();
this.productBindingSource.DataSource = dc.GetTable<Product>();
productDataGridView.DataSource = productBindingSource;
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
this.productBindingSource.Filter = string.Format("ProductName LIKE '*{0}*'",
textBox1.Text);
}
Make sure your TextChanged event is wired up and actually running. Also, I took qry out of the example since you weren't using it anywhere in the posted code.
older edits:
You shouldn't have to reset the DataSource on the grid.
Try changing it to this:
private void textBox1_TextChanged(object sender, EventArgs e) {
if (textBox1.Text == string.Empty) {
productBindingSource.RemoveFilter();
} else {
productBindingSource.Filter = string.Format("ProductName LIKE '*{0}*'", _
textBox1.Text);
}
}
I would avoid worrying about replacing those special characters at the moment. Get the filter working first.
Here is a working example with just a DataGridView and a TextBox on a form:
private DataTable dt = new DataTable("Test");
private BindingSource bs;
public Form1() {
InitializeComponent();
dt.Columns.Add("ProductName", typeof(string));
DataRow dr1 = dt.NewRow();
dr1["ProductName"] = "One A";
dt.Rows.Add(dr1);
DataRow dr2 = dt.NewRow();
dr2["ProductName"] = "One B";
dt.Rows.Add(dr2);
DataRow dr3 = dt.NewRow();
dr3["ProductName"] = "Two A";
dt.Rows.Add(dr3);
DataRow dr4 = dt.NewRow();
dr4["ProductName"] = "Two B";
dt.Rows.Add(dr4);
bs = new BindingSource(dt, null);
dataGridView1.DataSource = bs;
}
private void textBox1_TextChanged(object sender, EventArgs e) {
if (textBox1.Text == string.Empty) {
bs.RemoveFilter();
} else {
bs.Filter = string.Format("ProductName LIKE '*{0}*'", textBox1.Text);
}
}
this work just fine for me!
this.productBindingSource.Filter = null;