So I have written my code but every time i try to execute it it says "exception unhandled System.InvalidOperationException: 'Fill: SelectCommand.Connection property has not been initialized.'" and it always shows it at the line that says da.Fill(dt);
please tell me how to fix it
namespace FairyTailHRSolution
{
public partial class Form1 : Form
{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
public Form1()
{
InitializeComponent();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
con=new SqlConnection(#"Data Source = LAPTOP-VHSGV41H\SQLEXPRESS; Initial Catalog = EmpDB; Integrated Security = True");
con.Open();
cmd = new SqlCommand("INSERT INTO FRYEMP (EmployeeID, EmployeeName, EmployeePosition, EmployeeSalary) VALUES (#EmployeeID, #EmployeeName, #EmployeePosition, #EmployeeSalary)", con);
cmd.Parameters.Add("#EmployeeID", textBox1.Text);
cmd.Parameters.Add("#EmployeeName", textBox2.Text);
cmd.Parameters.Add("#EmployeePosition", textBox3.Text);
cmd.Parameters.Add("#EmployeeSalary", textBox4.Text);
cmd.ExecuteNonQuery();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void find_Click(object sender, EventArgs e)
{
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
if(comboBox1.Text == "EmployeeID")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeID like #employeeID", con);
da.SelectCommand.Parameters.AddWithValue("#employeeID", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
else if (comboBox1.Text == "EmployeeName")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeName like #employeeName", con);
da.SelectCommand.Parameters.AddWithValue("#employeeName", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
The best practice for handling connection objects is to store them in a local variable and dispose them as soon as possible. You don't need to worry overhead opening and closing connections; they are actually managed in a pool and it's very efficient.
You are storing your connection at the class level and not handling the connection properly. If you store it at the class level, it could time out between button clicks, and it's taking up resources the whole time. Close or dipose the connection right away, which will return it to the connection pool.
To fix, follow this sort of pattern:
namespace FairyTailHRSolution
{
public partial class Form1 : Form
{
//Get rid of member variable for the connection. Add constant for connection string.
private const string ConnectionString = #"Data Source = LAPTOP-VHSGV41H\SQLEXPRESS; Initial Catalog = EmpDB; Integrated Security = True";
private void button1_Click(object sender, EventArgs e)
{
//Use using and use a local variable for the connection
using (var con=new SqlConnection(this.ConnectionString))
{
con.Open();
var cmd = new SqlCommand("INSERT INTO FRYEMP (EmployeeID, EmployeeName, EmployeePosition, EmployeeSalary) VALUES (#EmployeeID, #EmployeeName, #EmployeePosition, #EmployeeSalary)", con);
cmd.Parameters.Add("#EmployeeID", textBox1.Text);
cmd.Parameters.Add("#EmployeeName", textBox2.Text);
cmd.Parameters.Add("#EmployeePosition", textBox3.Text);
cmd.Parameters.Add("#EmployeeSalary", textBox4.Text);
cmd.ExecuteNonQuery();
}
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
if(comboBox1.Text == "EmployeeID")
{
//Create a new connection each time you need one
using (var con = new SqlConnection(this.ConnectionString))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeID like #employeeID", con);
da.SelectCommand.Parameters.AddWithValue("#employeeID", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
else if (comboBox1.Text == "EmployeeName")
{
using (var con = new SqlConnection(this.ConnectionString))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeName like #employeeName", con);
da.SelectCommand.Parameters.AddWithValue("#employeeName", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
your connection property is not intialised.Click button_click to have your connection intialised.or inside Textbox5_textchanged check for connection con.Isopen else intialize connection object again.
I think you shoul initialize connection object first of all.
You can change your code with the below code and pls return result:
private void textBox5_TextChanged(object sender, EventArgs e)
{
if(con == null)
{
con=new SqlConnection(#"Data Source = LAPTOP-VHSGV41H\SQLEXPRESS; Initial Catalog = EmpDB; Integrated Security = True");
}
if(con.State == ConnectionState.Closed)
{
con.Open();
}
SqlDataAdapter da = null;
DataTable dt = new DataTable();
if(comboBox1.Text == "EmployeeID")
{
da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeID like #employeeID", con);
da.SelectCommand.Parameters.AddWithValue("#employeeID", "%" + textBox5.Text + "%");
da.Fill(dt);
}
else if (comboBox1.Text == "EmployeeName")
{
da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeName like #employeeName", con);
da.SelectCommand.Parameters.AddWithValue("#employeeName", "%" + textBox5.Text + "%");
da.Fill(dt);
}
else
{
}
dataGridView1.DataSource = dt;
}
Your connection has not been initialized at the time you're textBox5 text has changed. Move it to your constructor.
namespace FairyTailHRSolution
{
public partial class Form1 : Form
{
SqlCommand cmd;
SqlConnection con;
SqlDataAdapter da;
public Form1()
{
InitializeComponent();
con=new SqlConnection(#"Data Source = LAPTOP-VHSGV41H\SQLEXPRESS; Initial Catalog = EmpDB; Integrated Security = True");
con.Open();
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
cmd = new SqlCommand("INSERT INTO FRYEMP (EmployeeID, EmployeeName, EmployeePosition, EmployeeSalary) VALUES (#EmployeeID, #EmployeeName, #EmployeePosition, #EmployeeSalary)", con);
cmd.Parameters.Add("#EmployeeID", textBox1.Text);
cmd.Parameters.Add("#EmployeeName", textBox2.Text);
cmd.Parameters.Add("#EmployeePosition", textBox3.Text);
cmd.Parameters.Add("#EmployeeSalary", textBox4.Text);
cmd.ExecuteNonQuery();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void label1_Click(object sender, EventArgs e)
{
}
private void label2_Click(object sender, EventArgs e)
{
}
private void find_Click(object sender, EventArgs e)
{
}
private void textBox5_TextChanged(object sender, EventArgs e)
{
if(comboBox1.Text == "EmployeeID")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeID like #employeeID", con);
da.SelectCommand.Parameters.AddWithValue("#employeeID", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
else if (comboBox1.Text == "EmployeeName")
{
SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, EmployeeName,EmployeePosition, EmployeeSalary FROM FRYEMP where EmployeeName like #employeeName", con);
da.SelectCommand.Parameters.AddWithValue("#employeeName", "%" + textBox5.Text + "%");
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
Related
System.Data.SqlClient.SqlException: Conversion failed when converting
the varchar value 'System.Data.DataRowView' to data type int.
How to convert?
public partial class FrmItems : MaterialSkin.Controls.MaterialForm
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=G:\Users\Admin\source\repos\Elektrokalkulace\Sklad.mdf;Integrated Security=True;Connect Timeout=30");
SqlDataAdapter dt;
DataTable dtCategories = new DataTable();
DataTable dtSubCategories = new DataTable();
DataTable dtItems = new DataTable();
public FrmItems()
{
InitializeComponent();
dt = new SqlDataAdapter("SELECT * FROM Categories", conn);
dt.Fill(dtCategories);
CbxCat.DataSource = dtCategories;
CbxCat.DisplayMember = "NameCat";
CbxCat.ValueMember = "CatId";
var skinManager = MaterialSkinManager.Instance;
skinManager.AddFormToManage(this);
skinManager.Theme = MaterialSkinManager.Themes.DARK;
skinManager.ColorScheme = new ColorScheme(Primary.BlueGrey800, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE);
}
private void FrmItems_Load(object sender, EventArgs e)
{
// TODO: Tento řádek načte data do tabulky 'skladDataSet.Items'. Můžete jej přesunout nebo jej odstranit podle potřeby.
this.itemsTableAdapter.Fill(this.skladDataSet.Items);
}
private void CbxCat_SelectedIndexChanged(object sender, EventArgs e)
{
dtSubCategories.Clear();
dt = new SqlDataAdapter("SELECT * FROM Subcategories WHERE CatId='"+ CbxCat.SelectedValue +"'", conn);
dt.Fill(dtSubCategories);
CbxSubcat.DataSource = dtSubCategories;
CbxSubcat.DisplayMember = "NameSubCat";
CbxSubcat.ValueMember = "SubCatId";
}
private void CbxSubcat_SelectedIndexChanged(object sender, EventArgs e)
{
dtItems.Clear();
dt = new SqlDataAdapter("SELECT * FROM Items WHERE SubCatId='" + CbxSubcat.SelectedValue + "'", conn);
dt.Fill(dtItems);
dataGridViewItem.DataSource = dtItems;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
FrmHlavniMenu menu = new FrmHlavniMenu();
menu.Show();
this.Hide();
}
}
You claim it is failing on the second line below?
dt = new SqlDataAdapter("SELECT * FROM Subcategories WHERE CatId='"+ CbxCat.SelectedValue +"'", conn);
dt.Fill(dtSubCategories);
If CatId is an INT then this will fail because of the apostrophes (') surrounding the value. And please use parameters:
dt = new SqlDataAdapter("SELECT * FROM Subcategories WHERE CatId = #CatId", conn);
dt.SelectCommand.Parameters.AddWithValue("#CatId", CbxCat.SelectedValue);
dt.Fill(dtSubCategories);
Secondly, what is the type of CbxCat.SelectedValue? If it returns a string then you will need to parse the value as an integer: int.Parse(CbxCat.SelectedValue)
But the exception suggests it is actually of type System.Data.DataRowView. In that case you need to access the the item property, for example, CbxCat.SelectedValue["CategoryId"]
See for more info on DataRowView:
https://learn.microsoft.com/en-us/dotnet/api/system.data.datarowview.item?view=netframework-4.8#System_Data_DataRowView_Item_System_String_
I finally solved it this way. It took me a lot of effort, but it was worth it. Thank you all for your support and thank you very very much.
enter code here
public partial class FrmItems : MaterialSkin.Controls.MaterialForm
{
SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=G:\Users\Admin\source\repos\Elektrokalkulace\Stock.mdf;Integrated Security=True;Connect Timeout=30");
int CatId;
public FrmItems()
{
InitializeComponent();
refreshCat();
var skinManager = MaterialSkinManager.Instance;
skinManager.AddFormToManage(this);
skinManager.Theme = MaterialSkinManager.Themes.DARK;
skinManager.ColorScheme = new ColorScheme(Primary.BlueGrey800, Primary.BlueGrey900, Primary.BlueGrey500, Accent.LightBlue200, TextShade.WHITE);
}
private void FrmItems_Load(object sender, EventArgs e)
{
}
private void refreshCat()
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Categories", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
CbxCat.DisplayMember = "NameCat";
CbxCat.ValueMember = "CatId";
CbxCat.DataSource = dt;
}
private void CbxCat_SelectedIndexChanged(object sender, EventArgs e)
{
if (CbxCat.SelectedValue.ToString() != null)
{
CatId = Convert.ToInt32(CbxCat.SelectedValue.ToString());
refreshSubcat(CatId);
}
}
private void refreshSubcat(int CatId)
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Subcategories WHERE CatId=#CatId", conn);
cmd.Parameters.AddWithValue("CatId", CatId);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
CbxSubcat.DisplayMember = "NameSubcat";
CbxSubcat.ValueMember = "SubcatId";
CbxSubcat.DataSource = dt;
}
private void CbxSubcat_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT * FROM Items WHERE SubCatId='" + CbxSubcat.SelectedValue + "'", conn);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
conn.Close();
dataGridViewItem.DataSource = dt;
}
private void pictureBox1_Click(object sender, EventArgs e)
{
FrmMainMenu menu = new FrmMainMenu();
menu.Show();
this.Hide();
}
}
enter code here
I am trying to do edit inside grid view. When I click edit button to update record in text box it shows previous record. Please check. I think the error is in Row updating event.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
fill_grd1();
}
}
public void fill_grd1()
{
con.Open();
SqlCommand cmd = new SqlCommand("usp_country_get", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
grd1.DataSource = ds;
grd1.DataBind();
}
else
{
grd1.DataSource = null;
grd1.DataBind();
}
con.Close();
}
protected void savebtn_Click(object sender, EventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("usp_country_insert", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#cname", txtcname.Text);
cmd.ExecuteNonQuery();
con.Close();
fill_grd1();
}
protected void grd1_RowEditing(object sender, GridViewEditEventArgs e)
{
grd1.EditIndex = e.NewEditIndex;
fill_grd1();
}
protected void grd1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
int id = int.Parse(grd1.DataKeys[e.RowIndex].Value.ToString());
con.Open();
SqlCommand cmd = new SqlCommand("usp_country_delete", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#cid", id);
cmd.ExecuteNonQuery();
con.Close();
fill_grd1();
}
protected void grd1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox TB1 = (TextBox)grd1.Rows[e.RowIndex].FindControl("edittxtcname");
int id = int.Parse(grd1.DataKeys[e.RowIndex].Value.ToString());
con.Open();
SqlCommand cmd = new SqlCommand("usp_country_update", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#cid", id);
cmd.Parameters.AddWithValue("#cname", TB1.Text);
cmd.ExecuteNonQuery();
con.Close();
grd1.EditIndex = -1;
fill_grd1();
}
protected void grd1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
grd1.EditIndex = -1;
fill_grd1();
}
protected void grd1_RowDataBound(object sender, GridViewRowEventArgs e)
{
}
protected void grd1_RowCommand(object sender, GridViewCommandEventArgs e)
{
con.Open();
SqlCommand cmd = new SqlCommand("usp_country_status_change", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#cid", e.CommandArgument);
cmd.ExecuteNonQuery();
con.Close();
fill_grd1();
}
This is how my code really looks and performs. I have been trying to do filtering data according to comboboxes that I fill from the database and then to show data on the datagridview. Because I'm a beginner in coding, it has been really hard to write the combobox populating codes. I really searched in internet, read most of the titles. Is there any way to do this after all selections are done and maybe with the text is written in textbox and the search button (I created) clicked according to
the selections datagridview shows.
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;
namespace KPI_Tool
{
public partial class SearchForm : Form
{
static SqlConnection conn = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\010495\Desktop\KPI_Tool\KPI_Tool\KPI_Store.mdf;Integrated Security=True");
public SearchForm()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'kPI_StoreDataSet1.Store' table. You can move, or remove it, as needed.
this.myAdapter.Fill(this.myDataSet.Store);
}
private void Group_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox1.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT GroupN FROM Store WHERE GroupN IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["GroupN"].ToString());
}
conn.Close();
}
private void Tech_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox2.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT Tech_Area FROM Store WHERE Tech_Area IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox2.Items.Add(dr["Tech_Area"].ToString());
}
conn.Close();
}
private void Level_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox3.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT LevelOf FROM Store WHERE LevelOf IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox3.Items.Add(dr["LevelOf"].ToString());
}
conn.Close();
}
private void Domain_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox4.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT DomainN FROM Store WHERE DomainN IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox4.Items.Add(dr["DomainN"].ToString());
}
conn.Close();
}
private void Type_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox5.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT TypeN FROM Store WHERE TypeN IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox5.Items.Add(dr["TypeN"].ToString());
}
conn.Close();
}
private void Severity_DropDown(object sender, EventArgs e)
{
conn.Open();
comboBox6.Items.Clear();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT DISTINCT Severity FROM Store WHERE Severity IS NOT NULL";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox6.Items.Add(dr["Severity"].ToString());
}
conn.Close();
}
private void AlertTB_Click(object sender, MouseEventArgs e)
{
AlertTB.Clear();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void ListB_Click(object sender, EventArgs e)
{
}
private void ClearB_Clicked(object sender, EventArgs e)
{
comboBox1.SelectedIndex = -1;
comboBox2.SelectedIndex = -1;
comboBox3.SelectedIndex = -1;
comboBox4.SelectedIndex = -1;
comboBox5.SelectedIndex = -1;
comboBox6.SelectedIndex = -1;
AlertTB.Clear();
AlertTB.Text = "Write Here..";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
myBindingSource.Filter = "GroupN= '{0}'"+comboBox1.SelectedItem.Te;
conn.Close();
}
}
}
Here is my User Interface. I'm using Visual Studio Professional 2013. Please explain to me with very basic sentences. I want to learn the logic, the structure behind the code.
If you want to filter the gridview according to the text you entered in the textbox you can refer to my blog post
http://dotnetsolutionsbyankit.blogspot.in/2013/04/filter-gridview-as-you-type-in-textbox.html
so you will get an idea how to do it.
If you face any problem let me know in comment.
public static DataSet SQLGetData(string connectionString, string commandString)
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
DataSet DS = new DataSet();
DataTable DT = new DataTable("Table1");
try
{
connection.Open();
SqlCommand command = new SqlCommand(commandString, connection);
//command.CommandTimeout = 3000;
SqlDataReader read = command.ExecuteReader();
DS.Tables.Add(DT);
DS.Load(read, LoadOption.PreserveChanges, DS.Tables[0]);
}
catch (SqlException e)
{
System.Windows.Forms.MessageBox.Show(e.Message);
}
finally
{
connection.Close();
}
return DS;
}
}
private void SetFilter()
{
string command = "SELECT * FROM Store";
int count = 0;
if (comboBox1.Text != "")
{
command = command + " WHERE GroupN = '" + comboBox1.Text + "'";
count = count + 1;
}
if (comboBox2.Text != "")
{
if (count == 0)
{
command = command + " WHERE Tech_Area = '" + comboBox2.Text + "'";
}
else
{
command = command + " AND Tech_Area = '" + comboBox2.Text + "'";
}
count = count + 1;
}
if (comboBox3.Text != "")
{
if (count == 0)
{
command = command + " WHERE LevelOf = '" + comboBox3.Text + "'";
}
else
{
command = command + " AND LevelOf = '" + comboBox3.Text + "'";
}
count = count + 1;
}
// comboBox4, comboBox5, comboBox6
string connStr; //Connection string;
DataSet DS = new DataSet();
DS = SQLGetData(connStr, command);
DataGridView1.DataSource = DS.Tables[0];
}
I want the DataGridView gets updated when DataTable changes (myAdapter.DeleteCommand = cmd;).
Please help me. Thanks
My code is:
1.
public void DoCommand(String commandText, ActionType actionType, SqlParameter[] sqlParameter)
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = getConnection();
cmd.CommandText = commandText;
cmd.Parameters.AddRange(sqlParameter);
if (actionType == ActionType.Insert)
myAdapter.InsertCommand = cmd;
else if (actionType == ActionType.Update)
myAdapter.UpdateCommand = cmd;
else if (actionType == ActionType.Delete)
myAdapter.DeleteCommand = cmd;
cmd.ExecuteNonQuery();
}
}
2.
DataTable dt;
private void frmCustomers_Load(object sender, EventArgs e)
{
dt = obj.SelectCustomer();
dgCustomer.DataSource = localDt;
}
3.
private void btnDeleteCustomer_Click(object sender, EventArgs e)
{
obj.DoCommand("delete from tbl_customer where customer_id = 1", ActionType.Delete);
}
I am building a windows application using C#. In my login form, I'm getting Select Command property has not been initialized before calling fill method.
Here is the code:
public partial class frmlogin : Form
{
SqlConnection con = new SqlConnection("Data Source=TH07L019;Initial Catalog=loginerror;Integrated Security=True");
DataTable dt = new DataTable();
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = new SqlDataAdapter();
public frmlogin()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
cmd.Connection = con;
}
private void button1_Click(object sender, EventArgs e)
{
con.Open();
cmd.CommandText = "select * from login where username='" + txt1.Text + "' and password='" + txt2.Text +"'";
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
frmmain main = new frmmain();
main.Show();
}
else
{
MessageBox.Show("Please enter correct name and passowrd", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
You have to specify select command of SqlDataAdapter before filling your table. You are not doing it. Your SqlCommand object is not connected in any way to your SqlDataAdapter.
adp.SelectCommand=cmd;
Another way to accomplish would be to simply pass the SQLCommand as an argument into your data adapter as follows -
SqlCommand cmd = new SqlCommand();
SqlDataAdapter adp = new SqlDataAdapter(cmd);
SQL Data Adapter interacts with the data table. It is used to fill the Data Table from SQL Server DataBase. Before, filling the Data Table, the Data Adapter should know the command it is going to execute. So we have to fill the object of SQL Command Type i.e
SqlDataAdapter da = new SqlDataAdapter(cmd);
Here cmd is the object of SQL Command.
Now, the Data Adapter will know which command to execute before filling the data table.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace Employees_Details_Management_System
{
public partial class ShowEmpDtlsFrm : Form
{
SqlConnection con = new SqlConnection(#"Data Source = (local); Initial Catalog = sp_emp; Integrated Security = True");
public SqlCommand cmd { get; private set; }
// private SqlCommand cmd;
public ShowEmpDtlsFrm()
{
InitializeComponent();
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
ShwEmpDtlsLbl.Text = "Employee Database Management";
comboBox1.Text = "Click";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void DataGridChk()//Check if DataGrid is empty or not
{
if (dataGridView1.RowCount == 1)
{
dataGridView1.Visible = false;
MessageBox.Show("The Given " + comboBox1.Text+ " is Invalid \nEnter Valid " + comboBox1.Text);
}
}
public void DbDataFetch(String Qry)//For Fetching data from database
{
SqlCommand cmd = new SqlCommand(Qry, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "emp");
dataGridView1.DataSource = ds.Tables["emp"].DefaultView;
DataGridChk();
}
public void SrchBtn_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "Employee ID" || comboBox1.Text == "Department ID" || comboBox1.Text == "Manager ID")
{
if (textBox1.Text != "")
{
con.Open();
dataGridView1.Visible = true;
if (comboBox1.Text == "Employee ID")
{
string Qry = "select * from emp where emp_id='" + textBox1.Text + "' ";
DbDataFetch(Qry);
}
else if (comboBox1.Text == "Department ID")
{
string Qry = "select * from emp where dep_id='" + textBox1.Text + "' ";
DbDataFetch(Qry);
}
else if (comboBox1.Text == "Manager ID")
{
string Qry = "select * from emp where manager_id='" + textBox1.Text + "' ";
DbDataFetch(Qry);
}
con.Close();
}
else
{
MessageBox.Show("Please Enter the ID...");
}
}
else
{
MessageBox.Show("Choose Valid Option...");
}
}
catch (System.Data.SqlClient.SqlException sqlException)
{
System.Windows.Forms.MessageBox.Show(sqlException.Message);
con.Close();
}
}
private void button1_Click(object sender, EventArgs e)
{
EmpDtlsFrm edf = new EmpDtlsFrm();
edf.Show();
this.Hide();
}
}
}