Solved

display data in text field from data base for updating

Posted on 2016-11-11
6
57 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
  • 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
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

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…

776 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