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
Related
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)
{
}
}
}
I am trying to get the selectedindex of listbox 1 and 2 and update my databasetable based on the values selected in the two listboxes, but can't find a way to get the selectedindexes into my sql statement. Any suggestions?
private void Form1_Load(object sender, EventArgs e)
{
String cs = "Database=something;User=-;Password=-";
MySqlConnection dbconn = new MySqlConnection(cs);
dbconn.Open();
DataSet ds = new DataSet();
MySqlDataAdapter adapter = new MySqlDataAdapter(
"select * from reservasjon WHERE Rom_nr IS NULL ", dbconn);
adapter.Fill(ds);
this.listBox1.DataSource = ds.Tables[0];
this.listBox1.DisplayMember = "Rnr";
}
private void button1_Click(object sender, EventArgs e)
{
String cs = "Database=something;User=-;Password=-";
MySqlConnection dbconn = new MySqlConnection(cs);
dbconn.Open();
DataSet ds2 = new DataSet();
MySqlDataAdapter adapter2 = new MySqlDataAdapter(
"select * from rom WHERE etasje = '1' AND opptatt='1'", dbconn);
adapter2.Fill(ds2);
this.listBox2.DataSource = ds2.Tables[0];
this.listBox2.DisplayMember = "Rom_nr";
}
private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string value1 = listBox1.SelectedIndex.ToString();
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
string value2 = listBox2.SelectedIndex.ToString();
}
private void button4_Click(object sender, EventArgs e)
{
string value1 = listBox2.Text;
string value2 = listBox1.Text;
MySqlDataReader dr = null;
try
{
String cs = "Database=something;User=-;Password=-";
string selectStatement = "UPDATE reservasjon SET Rom_nr='102' WHERE Rnr='2';";
System.Data.DataTable dt = new System.Data.DataTable();
MySqlConnection dbconn = new MySqlConnection(cs);
dbconn.Open();
MySqlDataAdapter sqlDa = new MySqlDataAdapter();
sqlDa.SelectCommand = new MySqlCommand(selectStatement, dbconn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(sqlDa);
sqlDa.Fill(dt);
dt.Rows[0]["Rnr"] = "";
sqlDa.UpdateCommand = cb.GetUpdateCommand();
sqlDa.Update(dt);
}
catch (Exception s)
{
Console.WriteLine(s.Message);
}
}
This should do the trick :
private void button4_Click(object sender, EventArgs e)
{
string value1 = listBox2.Text;
string value2 = listBox1.Text;
MySqlDataReader dr = null;
try
{
String cs = "Database=something;User=-;Password=-";
string selectStatement = "UPDATE reservasjon SET Rom_nr='"+value2+"' WHERE Rnr='"value1+"';";
System.Data.DataTable dt = new System.Data.DataTable();
MySqlConnection dbconn = new MySqlConnection(cs);
dbconn.Open();
MySqlDataAdapter sqlDa = new MySqlDataAdapter();
sqlDa.SelectCommand = new MySqlCommand(selectStatement, dbconn);
MySqlCommandBuilder cb = new MySqlCommandBuilder(sqlDa);
sqlDa.Fill(dt);
dt.Rows[0]["Rnr"] = "";
sqlDa.UpdateCommand = cb.GetUpdateCommand();
sqlDa.Update(dt);
}
catch (Exception s)
{
Console.WriteLine(s.Message);
}
}
That's cause your variable value1 and value2 is not available outside the event handler method since you made them local. Declare them globally or just use the listBox1.SelectedIndex.ToString() directly in your SQL query
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 am facing a problem do not know how to set this problem the problem is that my project working fine but when i delete all the rows from sql databse its not show grid kindly help
your response will be highly appreciated
Here is my Code Behind
public partial class Web_grid : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindData();
}
}
protected void BindData()
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
DataSet ds = new DataSet();
conne.Open();
string cmdstr = "SELECT * FROM OPR1 ";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(ds);
cmd.ExecuteNonQuery();
conne.Close();
GridView1.DataSource = ds;
GridView1.DataBind();
// GridView1.DataSource =null;
// GridView1.DataSource = ds;
// GridView1.DataBind();
//ds = null;
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
SqlConnection conne = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
conne.Open();
if (e.CommandName.Equals("ADD"))
{
Calendar txtOpenDate = (Calendar)GridView1.FooterRow.FindControl("txtOpenDate");
TextBox txtCloseDate = (TextBox)GridView1.FooterRow.FindControl("txtCloseDate");
DropDownList DropDownListoppr = (DropDownList)GridView1.FooterRow.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)GridView1.FooterRow.FindControl("DropDownListStages");
TextBox txtAddLine = (TextBox)GridView1.FooterRow.FindControl("txtAddLine");
TextBox txtStages = (TextBox)GridView1.FooterRow.FindControl("txtStages");
TextBox txtAddOppId = (TextBox)GridView1.FooterRow.FindControl("txtAddOppId");
string cmdstr = "insert into OPR1(OpenDate,CloseDate,SlpCode,Step_Id,Line,OpprId) values(#txtOpenDate,#txtCloseDate,#SlpCode,#Step_Id,#txtAddLine,#txtAddOppId)";
SqlCommand cmd = new SqlCommand(cmdstr, conne);
cmd.Parameters.AddWithValue("#txtOpenDate", txtOpenDate.TodaysDate);
cmd.Parameters.AddWithValue("#txtCloseDate", txtCloseDate.Text);
cmd.Parameters.AddWithValue("#Step_Id", DropDownListStages.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#SlpCode", DropDownListoppr.SelectedValue.ToString()); // SelectedItem.ToString());
cmd.Parameters.AddWithValue("#txtStages", txtStages.Text);
cmd.Parameters.AddWithValue("#txtAddLine", txtAddLine.Text);
cmd.Parameters.AddWithValue("#txtAddOppId", txtAddOppId.Text);
cmd.ExecuteNonQuery();
// this.TextBox1.Text = DropDownList1.SelectedItem.ToString();
// this.TextBox3.Text = DropDownList1.SelectedValue.ToString();
BindData();
conne.Close();
}
}
protected void GridView1_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.Footer)
{
DropDownList DropDownListoppr = (DropDownList)e.Row.FindControl("DropDownListoppr");
DropDownList DropDownListStages = (DropDownList)e.Row.FindControl("DropDownListStages");
DataTable CardCode = new DataTable();
DataTable CardCode1 = new DataTable();
SqlConnection connection = new SqlConnection("Data Source=192.168.0.6;Initial Catalog=TestDataBase;Persist Security Info=True;User ID=sa;Password=malick");
using (connection)
{
SqlCommand theCommand = new SqlCommand("select SlpCode,SlpName from OSLP ", connection);
SqlCommand theCommand1 = new SqlCommand("select Distinct StepId, Descript from OOST ", connection);
SqlDataAdapter adapter = new SqlDataAdapter(theCommand);
SqlDataAdapter adapter1 = new SqlDataAdapter(theCommand1);
adapter.Fill(CardCode);
adapter1.Fill(CardCode1);
//DropDownList7.DataSource = CardCode;
//DropDownList7.DataTextField = "SlpName";
//DropDownList7.DataValueField = "SlpCode";
//DropDownList7.DataBind();
if (CardCode.Rows.Count > 0)
{
for (int i = 0; i < CardCode.Rows.Count; i++)
{
string name3 = CardCode.Rows[i]["SlpName"].ToString();
string slpCode = CardCode.Rows[i]["SlpCode"].ToString();
DropDownListoppr.Items.Add(new ListItem(name3, slpCode));
}
}
if (CardCode1.Rows.Count > 0)
{
for (int j = 0; j < CardCode1.Rows.Count; j++)
{
string name4 = CardCode1.Rows[j]["Descript"].ToString();
string stageCode = CardCode1.Rows[j]["StepId"].ToString();
DropDownListStages.Items.Add(new ListItem(name4, stageCode));
}
}
}
}
}
No need of cmd.ExecuteNonQuery(); in BindData Method, As you are not performing any insert,delete or update operation.
try to add this property to your aspx gridview
EmptyDataText="someText"
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatext(v=vs.110).aspx
or you can use EmptyDataTemplate - just like TemplateField
https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.emptydatatemplate(v=vs.110).aspx
Good day to all. I have this code that populates the Datagridview. And I tried to edit it. But it seems I can't save any changes to database. Though I'm not getting any errors. Any help would be much appreciated. Thanks alot!
private void FrmViewCustomer_Load(object sender, EventArgs e)
{
string query = "SELECT CONCAT(firstname,', ',lastname) AS NAME, orderedgood AS OrderedGood FROM customer c;";
using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["default"].ConnectionString))
{
conn.Open();
using (MySqlCommand command = new MySqlCommand(query, conn))
{
using (adapter = new MySqlDataAdapter(command))
{
dataGridView1.Rows.Clear();
dataGridView1.AllowUserToAddRows = false;
DataTable dt = new DataTable();
adapter.Fill(dt);
dataGridView1.DataSource = dt;
}
}
}
}
private void button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
this.adapter.Update(dt);
}
MyTable
id name
1 John
2 Carl
3 Sam
C# Code behind:
public partial class Form1 : Form
{
DataTable dt = null;
DataGridView dgv = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dt = new DataTable();
using (MySqlConnection conn = new MySqlConnection("server=localhost;user=root;pwd=1234;database=test;"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select * from MyTable;";
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
}
conn.Close();
}
dgv = new DataGridView();
dgv.AllowUserToAddRows = false;
dgv.CellEndEdit += new DataGridViewCellEventHandler(dgv_CellEndEdit);
dgv.CellValidating += new DataGridViewCellValidatingEventHandler(dgv_CellValidating);
dgv.Dock = DockStyle.Fill;
dgv.DataSource = dt;
this.Controls.Add(dgv);
}
void dgv_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
{
if (e.ColumnIndex == 0)
{
dgv.CancelEdit();
}
}
void dgv_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{
string id = dt.Rows[e.RowIndex]["id"] + "";
string col = dt.Columns[e.ColumnIndex].ColumnName;
string data = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex].Value+"";
string sql = string.Format("UPDATE `MyTable` SET `{0}` = '{1}' WHERE ID = {2};", col, data, id);
using (MySqlConnection conn = new MySqlConnection("server=localhost;user=root;pwd=1234;database=test;"))
{
conn.Open();
using (MySqlCommand cmd = new MySqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
conn.Close();
}
}
}