Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 112
  • Last Modified:

display data in text field from data base for updating

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
Abdullah Abdulkarim
Asked:
Abdullah Abdulkarim
  • 3
  • 2
1 Solution
 
Éric MoreauSenior .Net ConsultantCommented:
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
 
Pawan KumarDatabase ExpertCommented:
Could you please explain more ?
0
 
Éric MoreauSenior .Net ConsultantCommented:
Pawan, who do you address this question to?
0
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
Pawan KumarDatabase ExpertCommented:
Hi Eric Sir,
The Question is for the author.


Regards,
Pawan
0
 
Abdullah AbdulkarimSenior IT supervisorAuthor Commented:
Yes eric , could you please  explain more ?
0
 
Éric MoreauSenior .Net ConsultantCommented:
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

Free Backup Tool for VMware and Hyper-V

Restore full virtual machine or individual guest files from 19 common file systems directly from the backup file. Schedule VM backups with PowerShell scripts. Set desired time, lean back and let the script to notify you via email upon completion.  

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now