How to bind gridview from database? - database

using System.Data.SqlClient;
namespace EHR
{
public partial class imagery : Form
{
SqlConnection con = new SqlConnection(#"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\Users\wittyse\Desktop\database_EHR\EHR.mdf;Integrated Security=True;Connect Timeout=30");
SqlCommand cmd;
DataTable dt2 = new DataTable();
public imagery()
{
InitializeComponent();
}
public void readdatagrid1()
{
//con.Open();
SqlDataAdapter dpeo = new SqlDataAdapter("Select Img_ID,PEOPLE_INFO.people_ID,PEOPLE_INFO.Name,Imgs,Result from PEOPLE_INFO,IMAGERY_DIAGNOSTIC,MG_NAM where IMAGERY_DIAGNOSTIC.Img_ID=MG_NAM.Mg_nm_ID and PEOPLE_INFO.people_ID=IMAGERY_DIAGNOSTIC.People_ID", con);
DataSet dpep = new DataSet();
dpeo.Fill(dpep, "IMAGERY_DIAGNOSTIC");
dataGridView1.DataSource = dpep.Tables["IMAGERY_DIAGNOSTIC"];
con.Close();
}
private void imagery_Load(object sender, EventArgs e)
{
//dataGridView1.DataSource = null;
readdatagrid1();
SqlDataAdapter dz = new SqlDataAdapter("Select * from MG_NAM order by Mg_nm_ID", con);
DataSet dzo = new DataSet();
dz.Fill(dzo, "MG_NAM");
comboBox1.DataSource = dzo.Tables["MG_NAM"];
comboBox1.DisplayMember = "Imgs";
SqlDataAdapter da = new SqlDataAdapter("Select Name from PEOPLE_INFO order by people_ID", con);
DataSet ds = new DataSet();
da.Fill(ds, "PEOPLE_INFO");
comboBox2.DataSource = ds.Tables["PEOPLE_INFO"];
comboBox2.DisplayMember = "Name";
con.Close();
}
public int comck=0;
public int idx;
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
con.Close();
string Query = "Select Mg_nm_ID,Imgs from MG_NAM where Imgs='" + comboBox1.Text + "'";
con.Open();
SqlCommand createCommand = new SqlCommand(Query, con);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
textBox4.Text = dr.GetInt32(0).ToString();
//textBox1.Text = dr.GetInt32(1).ToString();
idx = Convert.ToInt32(textBox4.Text);
}
dr.Close();
comck = 1;
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(id+" index is "+comboBox1.SelectedIndex,"info");
}
public int comck2 = 0;
public int id;
private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
{
con.Close();
string Query = "Select people_ID,Name from PEOPLE_INFO where Name='" + comboBox2.Text + "'";
con.Open();
SqlCommand createCommand = new SqlCommand(Query, con);
SqlDataReader dr = createCommand.ExecuteReader();
while (dr.Read())
{
textBox2.Text = dr.GetInt32(0).ToString();
//textBox1.Text = dr.GetInt32(1).ToString();
id = Convert.ToInt32(textBox2.Text);
}
dr.Close();
comck2 = 1;
}
private void button2_Click(object sender, EventArgs e)
{
if (comck == 0 & comck2 == 0 || textBox3.Text == "")
{
MessageBox.Show("you must select or inter data","info");
}
else
{
con.Close();
cmd = new SqlCommand("Insert into IMAGERY_DIAGNOSTIC(People_ID,Mg_Nam,Result) values ('" + id + "','" + idx + "','" + textBox3.Text + "')", con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Added new IMAGERY DIAGNOSTIC ", "ADD", MessageBoxButtons.OK, MessageBoxIcon.Information);
dataGridView1.DataSource = null;
con.Close();
readdatagrid1();
}
// MessageBox.Show("info save"+comboBox1.SelectedIndex," info ");
}
private void button3_Click(object sender, EventArgs e)
{
if (selectgrid == 0)
{ MessageBox.Show("you must select record to delet it","Info",MessageBoxButtons.OK,MessageBoxIcon.Information); }
else
{
cmd = new SqlCommand("Delete From IMAGERY_DIAGNOSTIC Where Img_ID='" + bindex + "'", con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("You delete recored successfully", "delete", MessageBoxButtons.OK, MessageBoxIcon.Information);
dataGridView1.DataSource = null;
con.Close();
readdatagrid1();
}
}
public int bindex;
public int selectgrid = 0;
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
if (e.RowIndex >= 0)
{
DataGridViewRow row = this.dataGridView1.Rows[e.RowIndex];
textBox1.Text = row.Cells["People_ID"].Value.ToString(); //roll type to update
comboBox2.Text = row.Cells["Name"].Value.ToString();
textBox3.Text = row.Cells["Result"].Value.ToString();
string dex = row.Cells["Img_ID"].Value.ToString();
bindex = Convert.ToInt32(dex); //Bld_ID in integer format | for Query
selectgrid = 1;
}
}
}
}

replace the following code dataGridView1.DataSource = dpep.Tables["IMAGERY_DIAGNOSTIC"];
with
dataGridView1.DataSource = new BindingSource { DataSource =dpep.Tables["IMAGERY_DIAGNOSTIC"] };

Related

C#: Windows Form creating table and and retrieve data from database by each dynamic button click

I am trying to develop a restaurant billing application in windows form.
so I created dynamic buttons.
now I need a table which will retrieve data from database for each button click.
How can it possible?
private void newb_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
// textBox1.Text = btn.Text;
connection con = new connection();
con.connecting();
// Button b = new Button();
int i = 0;
var query = "select itemname,itemcode,price from item_master where itemcode =" + btn.Name;
MySqlCommand cmd = new MySqlCommand(query, con.con);
while (i < 10)
{
MySqlDataAdapter sda = new MySqlDataAdapter();
DataTable dt = new DataTable();
sda.SelectCommand = cmd;
DataTable dbdataset = new DataTable();
sda.Fill(dbdataset);
BindingSource bsource = new BindingSource();
bsource.DataSource = dbdataset;
dataGridView1.DataSource = bsource;
// MessageBox.Show(btn.Name);
i++;
}
// sda.Update(dbdataset);
// =dataGridView1.Rows[0]
//// MySqlDataReader mdr;
//// mdr = cmd.ExecuteReader();
// while (mdr.Read())
// {
//// textBox1.Text = (mdr["itemname"].ToString());
// }
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}

Additional information: Syntax error (missing operator) in query expression 'pin='

I am trying to pass database value into a another from using visual studio windows form. How do I access the data outside the while loop? and save to a string and pass that value into form2. I keep getting this error when passing to form2: Additional information: Syntax error (missing operator) in query expression 'pin='
my code for form1:
namespace ATM
{
public partial class Form1 : Form
{
String conn_string = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Dro\\Desktop\\ATM\\Database11.accdb; Persist Security Info=False;";
OleDbConnection conn = null;
public int pinnumber = 3300;
public string dbpin;
public string oppin;
public Form1()
{
InitializeComponent();
}
private void button13_Click(object sender, EventArgs e)
{
runQuery();
//checks PIN is entered or not
if (textBox2.Text.Length == 0)
{
textBox2.Text = textBox2.Text + "----";
}
else if (dbpin == textBox2.Text)//checks whether pin is correct and then shows the form 2(menu)
{
Form2 menu = new Form2();
menu.Show();
this.Hide();
}
else
{
textBox1.Text = "The PIN is Incorrect! Try Again!";
}
}
private void button_click(object sender, EventArgs e)
{
if (textBox2.Text == "----")
{
textBox2.Clear();
textBox1.Clear();
}
if (textBox2.Text.Length < 4)
{
Button button = (Button)sender;
textBox2.Text = textBox2.Text + button.Text;
textBox2.PasswordChar = '*';
}
}
private void button12_Click(object sender, EventArgs e)
{
textBox2.Clear();
}
private void runQuery()
{
conn = new OleDbConnection(conn_string);
MessageBox.Show("successfully connected");
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM atmDB where pin="+textBox2.Text;
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
dbpin = dr["PIN"].ToString();
}
MessageBox.Show(dbpin);
}
}
}

fill textbox on second combobox selection changed in cascading combobox in windows form using c#

I have 2 cascading combo-box in windows form application. I have textbox for price and unit. when I select first combobox, second combobox gets populated. I want textbox for price and unit to be filled only on second combobox selection.
My problem is when the form is loaded both textboxes are filled with values from table and not on combobox selection changed.
my code is:
private void Purchase_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'supplierDataSet.Supplier' table. You can move, or remove it, as needed.
this.supplierTableAdapter.Fill(this.supplierDataSet.Supplier);
fillName();
comboBoxName.SelectedIndex = -1;
}
private void fillName()
{
string str = "Select distinct Item_Name from Item";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxName.DataSource = dtItem;
comboBoxName.DisplayMember = "Item_Name";
comboBoxName.ValueMember = "Item_Name";
}
}
}
}
private void fillMake()
{
string str = "Select Item_Make from Item Where Item_Name=#Item_Name";
using (SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand(str, con))
{
cmd.Parameters.AddWithValue("#Item_Name", comboBoxName.Text);
using (SqlDataAdapter adp = new SqlDataAdapter(cmd))
{
DataTable dtItem = new DataTable();
adp.Fill(dtItem);
comboBoxMake.DataSource = dtItem;
comboBoxMake.ValueMember = "Item_Make";
comboBoxMake.DisplayMember = "Item_Make";
}
}
}
}
private void comboBoxName_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxName.Text))
{
comboBoxMake.Enabled = true;
fillMake();
comboBoxMake.SelectedIndex = -1;
}
}
private void comboBoxMake_SelectedIndexChanged_1(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(comboBoxMake.Text))
{
textBoxPrice.Enabled = true;
textBoxUoM.Enabled = true;
}
SqlConnection con = new SqlConnection(#"Data Source=ashish-pc\;Initial Catalog=HMS;Integrated Security=True");
SqlCommand cmd = new SqlCommand("Select * from Item Where Item_Make='" + comboBoxMake.Text + "' AND Item_Name='" + comboBoxName.Text + "'", con);
SqlDataReader reader;
try
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
reader = cmd.ExecuteReader();
while (reader.Read())
{
textBoxPrice.Text = Convert.ToString(reader["Price"]);
textBoxUoM.Text = Convert.ToString(reader["Unit"]);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (con.State == ConnectionState.Open)
{
con.Close();
}
}
}
I am stuck here. please help.
Try changing SelectedIndex = -1 to SelectedItem = -1 in Purchase_Load and ComboBox1_SelectedIndexChanged.

CRUD operation in MVC with out Entity framework

Hi I am beginner in MVC , I am trying to achieve CRUD operation in MVC using SQL with out Entity Framework or LINQ-SQL class. I done well with insert and getting the details of the selected table but when coming to Edit, details and delete I am confused how to perform so can some one help me out.
This is my code
Create a new Employee
public ActionResult Index(Test test)
{
try
{
if (ModelState.IsValid)
{
test.insert(test);
test.Name = "";
test.LastName = "";
}
}
catch (Exception)
{
}
return View(test);
}
Display all results
public ActionResult display()
{
Test tst = new Test();
return View(tst.getList());
}
This is my code in class file
public class Test
{
public int EmpID { get; set; }
[Required]
[DisplayName("Name")]
public string Name { get; set; }
[Required]
[DisplayName("LastName")]
public string LastName { get; set; }
string strConnection = ConfigurationManager.ConnectionStrings["SomeDataBase"].ConnectionString.ToString();
public void insert(Test test)
{
using (SqlConnection con = new SqlConnection(strConnection))
{
SqlCommand cmd = new SqlCommand("insert into Employee values('" + test.Name + "','" + test.LastName + "')", con);
con.Open();
cmd.ExecuteNonQuery();
}
}
public List<Test> getList()
{
List<Test> _lstPoducts = new List<Test>();
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("select * from Employee", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Test _Products = new Test();
_Products.EmpID = Convert.ToInt16(dr["EmpID"].ToString());
_Products.Name = dr["FirstName"].ToString();
_Products.LastName = dr["LastName"].ToString();
_lstPoducts.Add(_Products);
}
return _lstPoducts;
}
public List<Test> edit(int id)
{
List<Test> _lstPoducts = new List<Test>();
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("select * from Employee where EmpID='" + id + "'", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Test _Products = new Test();
_Products.EmpID = Convert.ToInt16(dr["EmpID"].ToString());
_Products.Name = dr["FirstName"].ToString();
_Products.LastName = dr["LastName"].ToString();
_lstPoducts.Add(_Products);
}
return _lstPoducts;
}
}
Can some one help me how to do the remaining operations like Details, Edit update and Delete.
for Details you can use
public Test details(int id)
{
Test _products = new Test();
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("select * from Employee where EmpID='" + id + "'", con);
con.Open();
try{
SqlDataReader dr = cmd.ExecuteReader();
_products.EmpID = Convert.ToInt16(dr["EmpID"].ToString());
_products.Name = dr["FirstName"].ToString();
_products.LastName = dr["LastName"].ToString();
}
catch(exception ex)
{
/* Do Some Stuff */
}
return _products;
}
And from your Controller
public ActionResult Details(int id)
{
Test tst = new Test();
return tst.Details(id);
}
for Edit you can use
public Bool Edit(test tst)
{
SqlConnection con = new SqlConnection(strConnection);
SqlCommand cmd = new SqlCommand("UPDATE TABLE Employee SET FirstName='"+tst.Name+"',Lastname='"+tst.LastName+"' where EmpID='" + tst.EmpId + "'", con);
con.Open();
try{
SqlDataReader dr = cmd.ExecuteReader();
return true;
}
catch(exception ex)
{
/* Do Some Stuff */
}
}
And from your Controller
public ActionResult Edit(test tsts)
{
Test tst = new Test();
return tst.Edit(tsts);
}
and proceed similarly for the rest of the cases

Database Updating

I have a web app, where when a page loads, the address details are extracted from the database and displayed in the corresponding text-fields. However when I try to update and save the data, the data doesn't get updated.
However the same works fine when the extraction of data happens through the click of a button.
here's the code :
public partial class Address : System.Web.UI.Page
{
string global;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
global = Session["ID"].ToString();
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Server = INLD50045747A\\SQLEXPRESS; Database = MyDatabase;User ID = sa; Password = Welcome1; Trusted_Connection = False;");
//SqlConnection con = new SqlConnection("Data Source=.\\SQLEXPRESS; AttachDbFilename=|DataDirectory|\\MyDatabase.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("SELECT PermanentAdd,PermanentAdd2, HomePlace, HomeState, HomePin FROM EMPLOYEE_FULLADDRESS_TABLE WHERE EmployeeID = '" + global + "'", con);
SqlDataReader x = cmd.ExecuteReader();
while (x.Read())
{
TextBox1.Text = (string)x["PermanentAdd"];
TextBox1.Enabled = false;
TextBox5.Text = (string)x["PermanentAdd2"];
TextBox5.Enabled = false;
TextBox2.Text = (string)x["HomePlace"];
TextBox2.Enabled = false;
TextBox3.Text = (string)x["HomeState"];
TextBox3.Enabled = false;
State.Items.FindByText(State.SelectedItem.Text).Selected = false;
State.Items.FindByText(TextBox3.Text).Selected = true;
State.Enabled = false;
TextBox4.Text = (string)x["HomePin"];
TextBox4.Enabled = false;
}
x.Close();
con.Close();
}
}
protected void UpdateButton_Click(object sender, EventArgs e)
{
try
{
System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Server = INLD50045747A\\SQLEXPRESS; Database = MyDatabase;User ID = sa; Password = Welcome1; Trusted_Connection = False;");
//System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection("Data Source=.\\SQLEXPRESS; AttachDbFilename=|DataDirectory|\\MyDatabase.mdf;Integrated Security=True;User Instance=True");
con.Open();
// global = Session["ID"].ToString();
//string insert = "UPDATE EMPLOYEE_FULLADDRESS_TABLE SET PermanentAdd = #PermanentAdd, PermanentAdd2 = #PermanentAdd2, HomePlace = #HomePlace, HomeState= #HomeState, HomePin= #HomePin where EmployeeID = '" + global + "'";
SqlCommand cmd1 = new SqlCommand("UPDATE EMPLOYEE_FULLADDRESS_TABLE SET PermanentAdd = #PermanentAdd, PermanentAdd2 = #PermanentAdd2, HomePlace = #HomePlace, HomeState= #HomeState, HomePin= #HomePin where EmployeeID = '" + global + "'", con);
cmd1.Parameters.AddWithValue("#PermanentAdd", TextBox1.Text);
cmd1.Parameters.AddWithValue("#PermanentAdd2", TextBox5.Text);
cmd1.Parameters.AddWithValue("#HomePlace", TextBox2.Text);
if (State.SelectedItem.Text == "--Select--")
{
State.SelectedItem.Text = TextBox3.Text;
}
cmd1.Parameters.AddWithValue("#HomeState", State.SelectedItem.Text);
cmd1.Parameters.AddWithValue("#HomePin", TextBox4.Text);
cmd1.ExecuteNonQuery();
con.Close();
lblmsg.Text = "DATA Updated Successfully";
lblmsg.ForeColor = System.Drawing.Color.Green;
}
catch (Exception exp)
{
lblmsg.Text = exp.Message;
lblmsg.ForeColor = System.Drawing.Color.Red;
}
}
// static int count = 0;
protected void EditButton_Click(object sender, EventArgs e)
{
TextBox1.Enabled = true;
TextBox2.Enabled = true;
//TextBox3.Enabled = true;
TextBox4.Enabled = true;
TextBox5.Enabled = true;
State.Enabled = true;
}
please help.
I think you have commented out your global / employeeid assignment?
// global = Session["ID"].ToString();
You should also change this to a parameter in your SQL.

Resources