i have the done following coding, unable to get the it working..
i have a Table with Id, Product, FolderPath.
i have a comboBox2 where i need two column of data from above table "Id" & "Product" to been shown in comboBox2. Now if i select a Row from comboBox2 i need the textBox1 and textBox2 to be filled with "Product" and "FolderPath" based on the comboBox2 selection.
Like even though the comboBox2 shows "Id" & "Product" internally the value has to be "Id".
Following are my code; can someone help me on this.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
namespace WindowsFormsApp1
{
public partial class Main : Form
{
string connString;
SqlConnection conn;
public Main()
{
InitializeComponent();
}
private void Main_Load(object sender, EventArgs e)
{
connString = #"Data Source=(LocalDB)\MSSQLLocalDB;Initial Catalog=ifz001;";
conn = new SqlConnection(connString);
conn.Open();
Load_Products();
}
void Load_Products()
{
try
{
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM FileFolderPath", conn);
DataTable dt = new DataTable();
da.Fill(dt);
for (int i = 0; i < dt.Rows.Count; i++)
{
comboBox2.Items.Add(dt.Rows[i]["Product"].ToString());
comboBox2.ValueMember = dt.Rows[i]["Id"].ToString();
}
}
catch (Exception lp)
{
MessageBox.Show(lp.Message);
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
/*try
{*/
var pix = "SELECT * FROM FileFolderPath WHERE Id = '" + comboBox2.ValueMember + "'";
SqlCommand cmd = new SqlCommand(pix, conn);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
PID.Text = dr["Product"].ToString();
PPath.Text = dr["FolderPath"].ToString();
}
/*}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}*/
}
Achieved using below code changes:
void Load_Products()
{
try
{
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM FileFolderPath", conn);
DataTable dt = new DataTable();
da.Fill(dt);
for(int i = 0; i < dt.Rows.Count; i++)
{
string pid = dt.Rows[i]["Id"].ToString() as string;
string p = dt.Rows[i]["Product"].ToString();
comboBox2.Items.Add(p);
comboBox2.DisplayMember = p;
comboBox2.ValueMember = pid.ToString() as string;
}
}
catch (Exception lp)
{
MessageBox.Show(lp.Message);
}
}
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
var ppat = "SELECT * FROM FileFolderPath WHERE Id = '" + comboBox2.SelectedIndex + "' ++1";
SqlCommand cmd = new SqlCommand(ppat, conn);
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
foreach(DataRow dr in dt.Rows)
{
PID.Text = dr["Id"].ToString();
PPath.Text = dr["FolderPath"].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Related
I am trying to insert two listbox items in two columns of same table of a database .but i could not would you please help me.
Please find the code below:
public partial class Form1 : Form
{
public static string var = "";
SqlConnection con = new SqlConnection("Data Source=DESKTOP-6056TSF;Initial Catalog=LibararyManagement;Integrated Security=True");
Form2 f2 = new Form2();
public Form1()
{
InitializeComponent();
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("Select * From Attribute where Test_Id like '"+Form2.a+"' ", con);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
var arr = new Label[dt.Rows.Count];
for (var i = 0; i < dt.Rows.Count; i++)
{
var lab = new Label();
lab.Text = dt.Rows[i][1].ToString();
// Other properties sets for tbox
this.panel1.Controls.Add(lab);
arr[i] = lab;
lab.Location = new Point(32, 32 + (i * 32));
lab.Width = 62;
}
textbox();
}
void textbox()
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("Select * From Attribute Where Test_Id like '"+Form2.a+"' ", con);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
var arr = new TextBox[dt.Rows.Count];
for (var i = 0; i < dt.Rows.Count; i++)
{
var texbox = new TextBox();
//teexbox.Text = dt.Rows[i][0].ToString();
// Other properties sets for tbox
this.panel1.Controls.Add(texbox);
arr[i] = texbox;
texbox.Location = new Point(122,32 + (i * 32));
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach (TextBox text in panel1.Controls.OfType<TextBox>())
{
listBox2.Items.Add(text.Text);
}
foreach (Label lbl in panel1.Controls.OfType<Label>())
{
listBox1.Items.Add(lbl.Text);
}
foreach (var b in listBox2.Items)
{
string msg = b.ToString();
foreach (var a in listBox1.Items)
{
string message = a.ToString();
con.Open();
string saveStaff = "INSERT into Reg_Test_Atrribute(RTA_Name, RTA_Value , TR_Id ) " +
" VALUES ('" + message + "', '" + msg + "' ,'" + Form2.a + "');";
SqlCommand cmd = new SqlCommand(saveStaff, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Sucessfully Saved");
}
}
}
}
It is working but if dt.row.counts = 4 the nested loop runs 16 time
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 dyna
{
public partial class Form1 : Form
{
public static string var = "";
SqlConnection con = new SqlConnection("Data Source=DESKTOP-6056TSF;Initial Catalog=LibararyManagement;Integrated Security=True");
Form2 f2 = new Form2();
public Form1()
{
InitializeComponent();
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("Select * From Attribute where Test_Id like '"+Form2.a+"' ", con);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
var arr = new Label[dt.Rows.Count];
for (var i = 0; i < dt.Rows.Count; i++)
{
var lab = new Label();
lab.Text = dt.Rows[i][1].ToString();
// Other properties sets for tbox
this.panel1.Controls.Add(lab);
arr[i] = lab;
lab.Location = new Point(32, 32 + (i * 32));
lab.Width = 62;
}
textbox();
}
void textbox()
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("Select * From Attribute Where Test_Id like '"+Form2.a+"' ", con);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
var arr = new TextBox[dt.Rows.Count];
for (var i = 0; i < dt.Rows.Count; i++)
{
var texbox = new TextBox();
//teexbox.Text = dt.Rows[i][0].ToString();
// Other properties sets for tbox
this.panel1.Controls.Add(texbox);
arr[i] = texbox;
texbox.Location = new Point(122,32 + (i * 32));
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach (TextBox text in panel1.Controls.OfType<TextBox>())
{
listBox2.Items.Add(text.Text);
}
foreach (Label lbl in panel1.Controls.OfType<Label>())
{
listBox1.Items.Add(lbl.Text);
}
foreach (var b in listBox2.Items)
{
string msg = b.ToString();
foreach (var a in listBox1.Items)
{
string message = a.ToString();
con.Open();
string saveStaff = "INSERT into Reg_Test_Atrribute(RTA_Name, RTA_Value , TR_Id ) " +
" VALUES ('" + message + "', '" + msg + "' ,'" + Form2.a + "');";
SqlCommand cmd = new SqlCommand(saveStaff, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Sucessfully Saved");
}
}}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
}
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 dyna
{
public partial class Form1 : Form
{
public static string var = "";
SqlConnection con = new SqlConnection("Data Source=DESKTOP-6056TSF;Initial Catalog=LibararyManagement;Integrated Security=True");
Form2 f2 = new Form2();
public Form1()
{
InitializeComponent();
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("Select * From Attribute where Test_Id like '"+Form2.a+"' ", con);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
var arr = new Label[dt.Rows.Count];
for (var i = 0; i < dt.Rows.Count; i++)
{
var lab = new Label();
lab.Text = dt.Rows[i][1].ToString();
// Other properties sets for tbox
this.panel1.Controls.Add(lab);
arr[i] = lab;
lab.Location = new Point(32, 32 + (i * 32));
lab.Width = 62;
}
textbox();
}
void textbox()
{
con.Open();
SqlDataAdapter sda = new SqlDataAdapter("Select * From Attribute Where Test_Id like '"+Form2.a+"' ", con);
DataTable dt = new DataTable();
sda.Fill(dt);
con.Close();
var arr = new TextBox[dt.Rows.Count];
for (var i = 0; i < dt.Rows.Count; i++)
{
var texbox = new TextBox();
//teexbox.Text = dt.Rows[i][0].ToString();
// Other properties sets for tbox
this.panel1.Controls.Add(texbox);
arr[i] = texbox;
texbox.Location = new Point(122,32 + (i * 32));
}
}
private void button1_Click(object sender, EventArgs e)
{
foreach (TextBox text in panel1.Controls.OfType<TextBox>())
{
listBox2.Items.Add(text.Text);
}
foreach (Label lbl in panel1.Controls.OfType<Label>())
{
listBox1.Items.Add(lbl.Text);
}
con.Open();
String query = "INSERT INTO Reg_Test_Atrribute (RTA_Name,RTA_Value,TR_Id) VALUES(#RTA_Name,#RTA_Value,#TR_Id)";
SqlCommand command = new SqlCommand(query,con);
command.Parameters.Add(new SqlParameter("#RTA_Name", SqlDbType.VarChar));
foreach (var b in listBox2.Items)
{
command.Parameters["#RTA_Name"].Value = b.ToString();
}
command.Parameters.Add(new SqlParameter("RTA_Value", SqlDbType.VarChar));
command.Parameters.Add(new SqlParameter("#TR_Id", SqlDbType.VarChar));
foreach (var a in listBox1.Items)
{
command.Parameters["RTA_Value"].Value = a.ToString();
command.Parameters["#TR_Id"].Value = Form2.a.ToString();
command.ExecuteNonQuery();
}
con.Close();
/*con.Open();
string saveStaff = "INSERT into Reg_Test_Atrribute(RTA_Name, RTA_Value , TR_Id ) " +
" VALUES ('" + message + "', '" + msg + "' ,'" + Form2.a + "');";
SqlCommand cmd = new SqlCommand(saveStaff, con);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Sucessfully Saved");
*/
}
private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
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];
}
Apologies if this has been covered. The examples I seemed to find were more complicated than I need it to be
I'm trying to output the entire contents of an SQL table to a DatagridView when a button "Display All Records" is clicked
I'm having a bit of trouble, here is what I have so far
private void Button_Click_2(object sender, RoutedEventArgs e)
{
{
string query = "select * from student";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(DataGridView);
con.Close();
da.Dispose();
}
Here is all my code if you need to refer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True");
public MainWindow()
{
InitializeComponent();
establishConnection();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
Boolean postSuccess = false;
if (validation() == true)
{
SqlCommand details = new SqlCommand("INSERT INTO Student (Firstname, LastName, MatriculationNo, GradeOne, GradeTwo, GradeThree) VALUES (#FirstName, #LastName, #MatriculationNo, #GradeOne, #GradeTwo, #GradeThree)", con);
details.Parameters.AddWithValue("#FirstName", firstnameTextbox.Text);
details.Parameters.AddWithValue("#LastName", lastnameTextbox.Text);
details.Parameters.AddWithValue("#MatriculationNo", matriculationnoTextbox.Text);
details.Parameters.AddWithValue("#GradeOne", Component1Textbox.Text);
details.Parameters.AddWithValue("#GradeTwo", Component2Textbox.Text);
details.Parameters.AddWithValue("#GradeThree", Component3Textbox.Text);
con.Open();
details.ExecuteNonQuery();
postSuccess = true;
if (postSuccess)
{
MessageBox.Show("Details entered succesfully!");
firstnameTextbox.Clear();
lastnameTextbox.Clear();
matriculationnoTextbox.Clear();
Component1Textbox.Clear();
Component2Textbox.Clear();
Component3Textbox.Clear();
}
else
{
MessageBox.Show("Data not entered succesfully, please check DB connection");
}
con.Close();
}
}
private void establishConnection()
{
try
{
con.Open();
System.Diagnostics.Debug.Print("Connected to SQL database");
connectionLabel.Content = "Connected to SQL Database";
con.Close();
}
catch (Exception)
{
connectionLabel.Content = "not connected to sql database";
}
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
firstnameTextbox.Clear(); //Clears the first name textbox
lastnameTextbox.Clear(); //Clears the last name textbox
matriculationnoTextbox.Clear(); //Clears the Matriculation Number textbox
Component1Textbox.Clear(); //Clears the component one textbox
Component2Textbox.Clear(); //Clears the component two textbox
Component3Textbox.Clear(); //Clears the component three textbox
}
private Boolean validation()
{
if (!Regex.Match(firstnameTextbox.Text, "^[A-Z][a-zA-Z]*$").Success)
{
MessageBox.Show("Please Enter a valid First Name");
firstnameTextbox.Clear();
return false;
}
else
{
return true;
}
}
private void Button_Click_3(object sender, RoutedEventArgs e)
{
con.Open();
string sql = #"DELETE FROM Student;"; //Deleting all from Student table
SqlCommand purge = new SqlCommand(sql, con);
MessageBox.Show("Are you sure you want to purge the entire contents of the database?"); //Prompting user to make sure they want to delete
purge.ExecuteNonQuery(); //Execute purge query
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
{
string query = "select * from student";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(DataGridView);
con.Close();
da.Dispose();
}
}
}
}
Any help would be much appreciated, thank you
Just fill DataTable with your table and bind it to GridView.DataContext.
Like so:
First Add DataGrid in XAML editor <DataGrid Name="customDataGrid" ItemsSource="{Binding}">
then Code behind:
namespace WpfApplication4
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
string connectionString = #"Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True";
public MainWindow()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
DataTable table = null;
string query = "select * from student";
try
{
using (SqlConnection connection = new SqlConnection(this.connectionString))
{
connection.Open();
using (SqlDataAdapter adapter = new SqlDataAdapter(query, connection))
{
table = new DataTable();
adapter.Fill(table);
}
}
}
catch (Exception ex)
{
//handle caught exception
}
if (table != null)
{
customDataGrid.DataContext = table.DefaultView;
}
}
}
}
Binding part: customDataGrid.DataContext = table.DefaultView;
try this....
private void Button_Click_2(object sender, EventArgs e)
{
string query = "select * from student";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
DataTable dt = new DataTable();
// create data adapter
SqlDataAdapter da = new SqlDataAdapter(cmd);
// this will query your database and return the result to your datatable
da.Fill(dt);
con.Close();
da.Dispose();
dataGridView1.DataSource = dt;
}
MySqlCommand command = conn.CreateCommand();
command.CommandText = "Select * from student";
try
{
con.Open();
MySqlDataAdapter sda = new MySqlDataAdapter();
sda.SelectCommand = command;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bSource = new BindingSource();
bSource.DataSource = dbdataset;
dataGridView1.DataSource = bSource;
sda.Update(dbdataset);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
con.Close();
Try this
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();
}
}
}
I am trying to access all the records from database on a data grid view depending upon the type of user logging in through a form having 2 text-boxes for user_name and password respectively and on submit button records are displayed. But the code I have written is giving me the following error: The data types text and varchar are incompatible in the equal to operator. Please suggest changes.
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.Configuration;
using System.Data.SqlClient;
namespace Login_form
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string str = ConfigurationSettings.AppSettings["constring"].ToString();
SqlConnection sqlcon = new SqlConnection(str);
try
{
sqlcon.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
SqlCommand sqlcmd = new SqlCommand("select user_type from employee where user_name='" + textBox1.Text + "'and pwd= '" + textBox2.Text + "' ;", sqlcon);
SqlDataReader myReader = sqlcmd.ExecuteReader();
string user_type=string.Empty;
while(myReader.Read())
{
user_type= myReader["user_type"].ToString();
}
sqlcon.Close();
sqlcon.Open();
SqlCommand sqlcmd2 = new SqlCommand("select * from employee where user_type= '" +user_type + "'", sqlcon);
SqlDataReader myReader2 = sqlcmd2.ExecuteReader();
/* SqlDataAdapter sqladapter = new SqlDataAdapter(sqlcmd2);
DataSet ds = new DataSet();
sqladapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];*/
DataTable dt = new DataTable();
dt.Columns.Add("ID", typeof(string));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Email_ID", typeof(string));
dt.Columns.Add("Contact", typeof(string));
dt.Columns.Add("Address", typeof(string));
while (myReader2.Read())
{
DataRow dr = dt.NewRow();
dr["ID"] = myReader2["ID"];
dr["Name"] = myReader2["user_name"];
dr["Email_ID"] = myReader2["Email_ID"];
dr["Contact"] = myReader2["Contact"];
dr["Address"] = myReader2["Address"];
dt.Rows.Add(dr);
}
dataGridView1.DataSource = dt;
sqlcon.Close();
}
}
}
This is a simple Database Problem.
in the Database generation script change:
columnname text NULL,
to:
columnname varchar(number of chars) NULL,
in your case columnname would be "user_name" or "user_type"
this problem occurs, because SQL-Type text is !not compatible for comparison with strings!
as soon as you change the type from text to varchar() the operation should work