Solved

display data in text field from data base for updating

Posted on 2016-11-11
6
26 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 69

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 17

Expert Comment

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

Expert Comment

by:Éric Moreau
ID: 41885344
Pawan, who do you address this question to?
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 17

Expert Comment

by:Pawan Kumar Khowal
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 69

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

Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

Join & Write a Comment

Introduction: When running hybrid database environments, you often need to query some data from a remote db of any type, while being connected to your MS SQL Server database. Problems start when you try to combine that with some "user input" pass…
Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.
In this tutorial you'll learn about bandwidth monitoring with flows and packet sniffing with our network monitoring solution PRTG Network Monitor (https://www.paessler.com/prtg). If you're interested in additional methods for monitoring bandwidt…

707 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

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now