Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

display data in text field from data base for updating

Posted on 2016-11-11
6
Medium Priority
?
99 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 30

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
Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

 
LVL 30

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 2000 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

What is a Denial of Service (DoS)?

A DoS is a malicious attempt to prevent the normal operation of a computer system. You may frequently see the terms 'DDoS' (Distributed Denial of Service) and 'DoS' used interchangeably, but there are some subtle differences.

Question has a verified solution.

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

In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
In this article we will get to know that how can we recover deleted data if it happens accidently. We really can recover deleted rows if we know the time when data is deleted by using the transaction log.
Monitoring a network: how to monitor network services and why? Michael Kulchisky, MCSE, MCSA, MCP, VTSP, VSP, CCSP outlines the philosophy behind service monitoring and why a handshake validation is critical in network monitoring. Software utilized …
Visualize your data even better in Access queries. Given a date and a value, this lesson shows how to compare that value with the previous value, calculate the difference, and display a circle if the value is the same, an up triangle if it increased…

721 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