Solved

display data in text field from data base for updating

Posted on 2016-11-11
6
69 Views
Last Modified: 2016-11-26
I need  to display data in text field   to update all information i need from the table.
 when i tried to do it the error message  " Column named id cannot be found.
Parameter name: columnName"

this my code for all process:

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 ALraziApp2
{
    public partial class StoreMatrialLableCode : Form
    {

       
       
        SqlConnection sc = new SqlConnection(@"Data Source=Abdullah-PC\Sqlexpress;Initial Catalog=AlraziSystem;Integrated Security=True");
        
        SqlCommand cmd;
        SqlDataAdapter dr;

        [b]int id;[/b]
        

        public StoreMatrialLableCode()
        {
            InitializeComponent();

           
        }

        private void StoreMatrialLableCode_Load(object sender, EventArgs e)


        {

            if (sc.State == ConnectionState.Open)
            {
                sc.Close();
            }
            sc.Open();

            SqlCommand cmd = sc.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = " select * from Matrialinfo";
            cmd.ExecuteNonQuery();
            DataTable ds = new DataTable();
            SqlDataAdapter dm = new SqlDataAdapter(cmd);
            dm.Fill(ds);

            dataGridView1.DataSource = ds;







            // TODO: This line of code loads data into the 'alraziSystemDataSet6.Matrialinfo' table. You can move, or remove it, as needed.
            this.matrialinfoTableAdapter.Fill(this.alraziSystemDataSet6.Matrialinfo);
            // TODO: This line of code loads data into the 'alraziSystemDataSet6.Matrialinfo' table. You can move, or remove it, as needed.
          

            dataGridView1.RowsDefaultCellStyle.BackColor = Color.WhiteSmoke;
            dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Wheat;
            dataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.None;

            dataGridView1.DefaultCellStyle.SelectionBackColor = Color.LightSteelBlue;
            dataGridView1.DefaultCellStyle.SelectionForeColor = Color.Black;

            dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
            dataGridView1.Columns[1].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

            dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;

            dataGridView1.AllowUserToResizeColumns = false;
          
        }

        private void insert_Click(object sender, EventArgs e)
        {
              {
            try
            {
                //string S = @"(select count(*) from RecevedItems where Received_ID ='" + username.Text + "' )";


                SqlCommand cmd = new SqlCommand("insert into Matrialinfo(Material_Name,Material_Code,Mfg_Date,Exp_Dat,Manufac_BatchNo,Manufac_SupplierName,Quantity,GRN_No,Containers_No,Receipt_Date,Receivedby,QCBatch_No) Values('" + matrilname.Text + "','" + matrialcode.Text + "','" + mfgdate.Text + "','" + expdate.Text + "','" + manfucbatchno.Text + "','" + manfacsuppliername.Text + "','" + qty.Text + "','" + grnno.Text + "','" + containersno.Text + "','" + receiptdate.Text + "','" + receivedby.Text + "','" + qcbatchno.Text + "')", sc);
                sc.Open();
                //SqlCommand cmda = new SqlCommand(S, sc);
             
                //int count =(int)cmda.ExecuteScalar();
                //if (count > 0)
                {
                  //  MessageBox.Show("this user alrady exist");
                }
                //else
                {
                cmd.ExecuteNonQuery();
                MessageBox.Show(" user Matrial lablecode add Succefully");

                matrilname.Text = string.Empty;
                matrialcode.Text = string.Empty;
                mfgdate.Text = string.Empty;
                expdate.Text = string.Empty;
                manfucbatchno.Text = string.Empty;
                manfacsuppliername.Text = string.Empty;
                qty.Text = string.Empty;
                grnno.Text = string.Empty;
                containersno.Text = string.Empty;
                receiptdate.Text = string.Empty;
                receivedby.Text = string.Empty;
               qcbatchno.Text = string.Empty;
              


                sc.Close();
            }

           
              
            }

             catch (Exception ex)

            {
                MessageBox.Show(ex.Message);
             }
            finally
            {
                if (sc.State == ConnectionState.Open)
                    sc.Close();



                

            }
        }
        }

        private void textBox8_TextChanged(object sender, EventArgs e)
        {
        
        }
[b][b][b]
[/b][/b][/b]
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            id = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["id"].Value.ToString());


            SqlCommand cmd = sc.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = " select * from Matrialinfo where Material_Name=" + id + "";
            cmd.ExecuteNonQuery();
            DataTable ds = new DataTable();
            SqlDataAdapter dm = new SqlDataAdapter(cmd);
            dm.Fill(ds);
            foreach (DataRow dr in ds.Rows)
            {
                matrilname.Text = dr["Material_Name"].ToString();
            }

        }




        private void update_Click(object sender, EventArgs e)
        {
             SqlConnection _Conn = new SqlConnection();



               SqlConnection cn = new SqlConnection(@"Data Source=Abdullah-PC\Sqlexpress;Initial Catalog=AlraziSystem;Integrated Security=True");
               cn.Open();
               string sql = "UPDATE Matrialinfo SET Material_Name='" + matrilname.Text + "', Material_Code='" + matrialcode.Text + "', Mfg_Date='" + mfgdate.Text + "',Exp_Dat='" +expdate.Text+ "',Manufac_BatchNo='" + manfucbatchno.Text + "',Manufac_SupplierName='" + manfacsuppliername.Text + "',Quantity='" + qty.Text + "',GRN_No='" + grnno.Text + "',Containers_No='" + containersno.Text + "',Receipt_Date='" + receiptdate.Text + "',Receivedby='" + receivedby.Text + "' ,QCBatch_No='" + qcbatchno.Text + "' WHERE  Material_Name = " + matrilname.Text + "";
               SqlCommand cmd = new SqlCommand(sql, cn);
               cmd.ExecuteNonQuery();
               cmd.Dispose();
               cn.Close();
               MessageBox.Show(" Succefully updated");


                                          

                                            

                                            MessageBox.Show("تمت عملية تعديل بيانات الموظف بنجاح", "تعديل البيانات");

                                        

        }

        private void delete_Click(object sender, EventArgs e)
        {
            
            SqlConnection _Conn = new SqlConnection();





            try
            {

                if (matrilname.Text != "")
                {

                    DialogResult dresult = new DialogResult();

                    dresult = MessageBox.Show("هل انت متاكد من عملية حذف بيانات الموظف", "تحذير", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2);

                    if (dresult == DialogResult.Yes)
                    {

                        _Conn.ConnectionString = @"Data Source=Abdullah-PC\Sqlexpress;Initial Catalog=AlraziSystem;Integrated Security=True";

                        string _Delete_Emp = "Delete from  Matrialinfo WHERE (Material_Name = @Material_Name)";

                        SqlCommand  _Delete_Cmd = new SqlCommand(_Delete_Emp, _Conn);

                        _Conn.Open();

                        _Delete_Cmd.Connection = _Conn;

                        _Delete_Cmd.Parameters.AddWithValue("@Material_Name",  matrilname.Text);

                        _Delete_Cmd.ExecuteNonQuery();

                        _Conn.Close();

                        MessageBox.Show("تمت عملية حذف ابن العم بنجاح ", "نجاح الحذف");



                    }

                }

                else
                {

                    MessageBox.Show("الرجاء ادخال رقم التعريف", "خطأ في البيانات", MessageBoxButtons.OK, MessageBoxIcon.Error);


                   matrilname.Focus();

                }

            }

            finally
            {
                _Conn.Close();


            }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void Search_Click(object sender, EventArgs e)
        {

            if (MatrialNameSearch.Text != "")
            {

                SqlConnection _Conn = new SqlConnection();

                string _Select_Emp = "Select * From  Matrialinfo Where  Material_Name=@Material_Name";

                _Conn.ConnectionString =@"Data Source=Abdullah-PC\Sqlexpress;Initial Catalog=AlraziSystem;Integrated Security=True";

                _Conn.Open();

                SqlCommand _Select_Command = new SqlCommand(_Select_Emp, _Conn);

                _Select_Command.Parameters.AddWithValue("@Material_Name", matrilname.Text);

                SqlDataReader _Objreader = _Select_Command.ExecuteReader();

                _Objreader.Read();

                matrilname.Text = Convert.ToString(_Objreader["Material_Name"]);

                  
                string str = "SELECT * FROM Matrialinfo WHERE Material_Name LIKE '%" + MatrialNameSearch.Text + "%'";

                SqlDataAdapter da = new SqlDataAdapter(str, _Conn);

                DataSet ds = new DataSet();
                ds.Clear();
                _Conn.Close();
                da.Fill(ds, "Material_Name");

                dataGridView1.DataSource = ds;
                dataGridView1.DataMember = "Material_Name";

                dataGridView1.DataSource = ds;
                dataGridView1.DataMember = "Material_Name";

                matrilname.Text = string.Empty;

                

              
            
                }

            else
            {

                MessageBox.Show("please insert correct data", MessageBoxButtons.OK, MessageBoxIcon.Error);


                MatrialNameSearch.Focus();

            }
        }

        private void expdate_TextChanged(object sender, EventArgs e)
        {

        }

        private void groupBox1_Enter(object sender, EventArgs e)
        {

        }

        }
        }
        

        

       
    

Open in new window

0
Comment
Question by:Abdullah Abdulkarim
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
6 Comments
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41884642
in the CellContentClick event handler, you are referring to the id cell but you don't seem to have one!

And considering you are using the value in a select clause to filter against the Material_Name field, wouldn't it be that field/cell that you should retrieve?
0
 
LVL 28

Expert Comment

by:Pawan Kumar
ID: 41884994
Could you please explain more ?
0
 
LVL 70

Expert Comment

by:Éric Moreau
ID: 41885344
Pawan, who do you address this question to?
0
Complete VMware vSphere® ESX(i) & Hyper-V Backup

Capture your entire system, including the host, with patented disk imaging integrated with VMware VADP / Microsoft VSS and RCT. RTOs is as low as 15 seconds with Acronis Active Restore™. You can enjoy unlimited P2V/V2V migrations from any source (even from a different hypervisor)

 
LVL 28

Expert Comment

by:Pawan Kumar
ID: 41885373
Hi Eric Sir,
The Question is for the author.


Regards,
Pawan
0
 

Author Comment

by:Abdullah Abdulkarim
ID: 41885847
Yes eric , could you please  explain more ?
0
 
LVL 70

Accepted Solution

by:
Éric Moreau earned 500 total points
ID: 41886130
check these lines you have:
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            id = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["id"].Value.ToString());


            SqlCommand cmd = sc.CreateCommand();
            cmd.CommandType = CommandType.Text;
            cmd.CommandText = " select * from Matrialinfo where Material_Name=" + id + "";

Open in new window


you first say :
id = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells["id"].Value.ToString());

Open in new window


I am pretty sure your " Column named id cannot be found. Parameter name: columnName" error is coming from here! Which column do you want to retrieve here?

Then your last line:
cmd.CommandText = " select * from Matrialinfo where Material_Name=" + id + "";

Open in new window


Compares Material_Name to id. It sounds to me that xx_Name should be a noun but id is defined as an integer. It just does not seem right.
0

Featured Post

Migrating Your Company's PCs

To keep pace with competitors, businesses must keep employees productive, and that means providing them with the latest technology. This document provides the tips and tricks you need to help you migrate an outdated PC fleet to new desktops, laptops, and tablets.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
Use this article to create a batch file to backup a Microsoft SQL Server database to a Windows folder.  The folder can be on the local hard drive or on a network share.  This batch file will query the SQL server to get the current date & time and wi…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question