Модераторы: gambit

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Как удалить запись из DataGridView и эту же запись 
:(
    Опции темы
shark1
Дата 14.1.2008, 14:07 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 274
Регистрация: 10.11.2007

Репутация: нет
Всего: нет



Проблемма следующая.
Есть DataGridView загружаю данные,данные бандятся,затем есть txt_Finde ввожу информацию по которой происходит сортировка в DataGridView.Затем хочу удалить эту строку :

Код

private void btn_Delete_Click(object sender, EventArgs e)
        {
            OleDbConnection oleDbConnection = new OleDbConnection();
            
            try
            {
               
                //this.adapter1.DeleteCommand = new OleDbCommand();

                OleDbCommand command = new OleDbCommand("Delete * from Users where WorkNumber = " + this.txt_Find.Text, oleDbConnection);
                //this.adapter1.DeleteCommand.CommandText =

            //"Delete * from Users where WorkNumber = " + this.txt_Find.Text;

                //open the bridge between the application and the datasource
                this.oleDbConnection.Open();


                this.adapter1.DeleteCommand.Connection = oleDbConnection;

                //execute the qurey 
                this.adapter1.DeleteCommand.ExecuteNonQuery();

                //close the connection
                this.oleDbConnection.Close();

                MessageBox.Show("Record deleted Successfully \n \nItem CLEAR !!!", " Warning !!! Warning !!! Warning !!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);  //inform the user
                this.Close();


            }
            catch (System.Data.OleDb.OleDbException exp)
            {

                MessageBox.Show(exp.ToString());
            }
            finally
            {
                //close the connection
                this.oleDbConnection.Close();
            }


        }

и вот сдесь:
Код

this.adapter1.DeleteCommand.Connection = oleDbConnection;

 выподает такая ошибка :

Код

System.NullReferenceException was unhandled
  Message="Object reference not set to an instance of an object.

Подскажите что не так,зарание спасибо.
PM MAIL   Вверх
CYBERDREAM
Дата 14.1.2008, 14:13 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


I think, there4 I am
***


Профиль
Группа: Завсегдатай
Сообщений: 1096
Регистрация: 31.10.2006
Где: CyberLand

Репутация: 1
Всего: 28



Приветствую. Сдается мне у тебя oleDbConnection ни на что не ссылается  smile Хотя с OleDBCon.. не работал

Добавлено @ 14:22
по идее нужно добавить нечто вроде этого
Код

oleDbConn.ConnectionString=strConn;


http://forums.port80.asn.au/showthread.php?t=10246 авось поможет  smile 

Это сообщение отредактировал(а) CYBERDREAM - 14.1.2008, 14:23


--------------------
Ищем .Net, Java, Javascript разработчиков, Кипр, Лимассол. (знание английского необязательно)
Telegram, skype: kuchuk.artiom
PM MAIL WWW   Вверх
shark1
Дата 14.1.2008, 15:27 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 274
Регистрация: 10.11.2007

Репутация: нет
Всего: нет



Нет не помогло :( ,таже ошибка на той же строке :(.
PM MAIL   Вверх
CYBERDREAM
Дата 14.1.2008, 15:46 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


I think, there4 I am
***


Профиль
Группа: Завсегдатай
Сообщений: 1096
Регистрация: 31.10.2006
Где: CyberLand

Репутация: 1
Всего: 28



а ну напиши, где ты присваиваешь конекшин  smile 


--------------------
Ищем .Net, Java, Javascript разработчиков, Кипр, Лимассол. (знание английского необязательно)
Telegram, skype: kuchuk.artiom
PM MAIL WWW   Вверх
shark1
Дата 14.1.2008, 16:17 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 274
Регистрация: 10.11.2007

Репутация: нет
Всего: нет



Код

 OleDbConnection oleDbConnection = new OleDbConnection();
            try
            {
                OleDbCommand command = new OleDbCommand();//"Delete * from Users where WorkNumber = " + this.txt_Find.Text, oleDbConnection);
                
                oleDbConnection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Data\\Users_DB.mdb";
                

                 this.adapter1.DeleteCommand.Connection = oleDbConnection;
                this.adapter1.DeleteCommand = new OleDbCommand();                
                this.adapter1.DeleteCommand.CommandText =
                 "Delete * from Users where WorkNumber = " + this.txt_Find.Text;
                //open the bridge between the application and the datasource
                this.oleDbConnection.Open();


               

                //execute the qurey 
                this.adapter1.DeleteCommand.ExecuteNonQuery();

                //close the connection
                this.oleDbConnection.Close();

                MessageBox.Show("Record deleted Successfully \n \nDATABASE CLEAR !!!", " Warning !!! Warning !!! Warning !!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);  //inform the user
                this.Close();


            }
            catch (System.Data.OleDb.OleDbException exp)
            {

                MessageBox.Show(exp.ToString());
            }
            finally
            {
                //close the connection
                this.oleDbConnection.Close();
            }

PM MAIL   Вверх
mr.DUDA
Дата 14.1.2008, 20:36 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


3D-маньяк
****


Профиль
Группа: Экс. модератор
Сообщений: 8244
Регистрация: 27.7.2003
Где: город-герой Минск

Репутация: 8
Всего: 232



Самую первую строчку в твоём примере грохни, а то получается что создаёшь локальную переменную, а потом обращаешься уже через поле класса (this.oleDbConnection), которое 100% пустое на этот момент.


--------------------
user posted image
PM MAIL WWW   Вверх
shark1
Дата 15.1.2008, 08:54 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 274
Регистрация: 10.11.2007

Репутация: нет
Всего: нет



mr.DUDA ubral pervuyu stroku,no eto ne reshilo problemu :(
PM MAIL   Вверх
mr.DUDA
Дата 15.1.2008, 11:03 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


3D-маньяк
****


Профиль
Группа: Экс. модератор
Сообщений: 8244
Регистрация: 27.7.2003
Где: город-герой Минск

Репутация: 8
Всего: 232



Ошибка та же ? Полный код давай.


--------------------
user posted image
PM MAIL WWW   Вверх
shark1
Дата 15.1.2008, 11:33 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 274
Регистрация: 10.11.2007

Репутация: нет
Всего: нет




Вот код кнопки Delete.
Код

private void btn_Delete_Click(object sender, EventArgs e)
        {
            try
            {
                //OleDbCommand command = new OleDbCommand();//"Delete * from Users where WorkNumber = " + this.txt_Find.Text, oleDbConnection);
                
                oleDbConnection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Data\\Users_DB.mdb";                           

                 this.adapter1.DeleteCommand.Connection = oleDbConnection;
                this.adapter1.DeleteCommand = new OleDbCommand();                
                this.adapter1.DeleteCommand.CommandText =
                 "Delete * from Users where WorkNumber = " + this.txt_Find.Text;
                //open the bridge between the application and the datasource
                this.oleDbConnection.Open();              

                //execute the qurey 
                this.adapter1.DeleteCommand.ExecuteNonQuery();

                //close the connection
                this.oleDbConnection.Close();

                MessageBox.Show("Record deleted Successfully \n \nITEM CLEAR !!!", " Warning !!! Warning !!! Warning !!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);  //inform the user
                this.Close();


            }
            catch (System.Data.OleDb.OleDbException exp)
            {

                MessageBox.Show(exp.ToString());
            }
            finally
            {
                //close the connection
                this.oleDbConnection.Close();
            }


        }

PM MAIL   Вверх
mr.DUDA
Дата 15.1.2008, 14:25 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


3D-маньяк
****


Профиль
Группа: Экс. модератор
Сообщений: 8244
Регистрация: 27.7.2003
Где: город-герой Минск

Репутация: 8
Всего: 232



Перед строкой 7 добавь:
Код
this.oleDbConnection = new OleDbConnection();



--------------------
user posted image
PM MAIL WWW   Вверх
shark1
Дата 15.1.2008, 14:32 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 274
Регистрация: 10.11.2007

Репутация: нет
Всего: нет



Добавил, но и это не помогло :(.Ошибка осталась таже на той же строке.
PM MAIL   Вверх
mr.DUDA
Дата 15.1.2008, 15:06 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


3D-маньяк
****


Профиль
Группа: Экс. модератор
Сообщений: 8244
Регистрация: 27.7.2003
Где: город-герой Минск

Репутация: 8
Всего: 232



а  this.adapter1 тоже нигде не заполняется ?


--------------------
user posted image
PM MAIL WWW   Вверх
shark1
Дата 15.1.2008, 15:20 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 274
Регистрация: 10.11.2007

Репутация: нет
Всего: нет



Вот код : 

Код

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.IO;

namespace StoreImagesInSQLServer
{
    public partial class frmImagesStore : Form
    {
        private System.Data.DataTable dataTable;        
        public frmImagesStore()
        {
            InitializeComponent();
            //GetImagesFromDatabase();
        }


        //Get table rows from sql server to be displayed in Datagrid.
        void GetImagesFromDatabase()
        {
            
            try
            {
                //Initialize SQL Server connection.
                //SqlConnection conn = new SqlConnection(txtConnectionString.Text);
                OleDbConnection conn = new OleDbConnection();//txtConnectionString.Text
                conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Data\\Users_DB.mdb";
                //Initialize SQL adapter.
                //SqlDataAdapter adapter = new SqlDataAdapter("Select * from ImagesStore", conn);
                OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from Users", conn);

                //Initialize Dataset.
                DataSet ds = new DataSet();
                dataTable = ds.Tables.Add("Users");

                //Fill dataset with ImagesStore table.
                adapter.Fill(ds, "Users");
                
                
                //Fill Grid with dataset.
                dataGridView1.DataSource = ds.Tables["Users"];

                
                this.txt_WorkNumber.DataBindings.Add("Text", dataTable, "WorkNumber", true, DataSourceUpdateMode.OnPropertyChanged);
                this.txt_FirstName.DataBindings.Add("Text", dataTable, "FirstName", true, DataSourceUpdateMode.OnPropertyChanged);
                this.txt_LastName.DataBindings.Add("Text", dataTable, "LastName", true, DataSourceUpdateMode.OnPropertyChanged);
                this.txt_BirthDate.DataBindings.Add("Text", dataTable, "BirthDate", true, DataSourceUpdateMode.OnPropertyChanged);
                this.txt_Status.DataBindings.Add("Text", dataTable, "Status", true, DataSourceUpdateMode.OnPropertyChanged);
                this.txt_Telephone.DataBindings.Add("Text", dataTable, "Telephone", true, DataSourceUpdateMode.OnPropertyChanged);
                this.txt_Cellular.DataBindings.Add("Text", dataTable, "Cellular", true, DataSourceUpdateMode.OnPropertyChanged);
                this.txt_Address.DataBindings.Add("Text", dataTable, "Address", true, DataSourceUpdateMode.OnPropertyChanged);
                this.txt_Email.DataBindings.Add("Text", dataTable, "Email", true, DataSourceUpdateMode.OnPropertyChanged);
                this.rtb_Remarks.DataBindings.Add("Text", dataTable, "Remarks", true, DataSourceUpdateMode.OnPropertyChanged);
                this.pictureBox1.DataBindings.Add("Text", dataTable, "Photo", true, DataSourceUpdateMode.OnPropertyChanged);
                


                foreach (DataGridViewColumn column in dataGridView1.Columns) column.SortMode = DataGridViewColumnSortMode.NotSortable;               

              }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void cmdConnect_Click(object sender, EventArgs e)
        {
            //Fill datagrid with table rows.
            GetImagesFromDatabase();
        }

        //Open form to get new image file.
        private void cmdStoreNewImage_Click(object sender, EventArgs e)
        {
            frmNewImage fNew = new frmNewImage();
            //Supply connection string from this form to frmNewImage form.
            fNew.txtConnectionString.Text = txtConnectionString.Text;
            fNew.ShowDialog();
        }

        //When user changes row selection, display image of selected row in picture box.
        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                //Get image data from gridview column.
                byte[] imageData = (byte[])dataGridView1.Rows[e.RowIndex].Cells["Photo"].Value;

                //Initialize image variable
                Image newImage;
                //Read image data into a memory stream
                using (MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length))
                {
                    ms.Write(imageData, 0, imageData.Length);

                    //Set image variable value using memory stream.
                    newImage = Image.FromStream(ms, true);
                }

                //set picture
                pictureBox1.Image = newImage;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        

        private void btn_SaveInExcel_Click(object sender, EventArgs e)
        {
            ExcelAuto excel = new ExcelAuto();

            ArrayList array = new ArrayList();
            bool filled = true;

            /*if ((txt_WorkNumber.Text).Trim().Length.Equals(0))
            {
                errorProvider.SetError(txt_WorkNumber, "cannot be empty");
                filled = false;
            }
            if ((txt_FirstName.Text).Trim().Length.Equals(0))
            {
                errorProvider.SetError(txt_FirstName, "cannot be empty");
                filled = false;
            }
            if ((txt_LastName.Text).Trim().Length.Equals(0))
            {
                errorProvider.SetError(txt_LastName, "cannot be empty");
                filled = false;
            }
            if ((txt_BirthDate.Text).Trim().Length.Equals(0))
            {
                errorProvider.SetError(txt_BirthDate, "cannot be empty");
                filled = false;
            }
            if ((txt_Status.Text).Trim().Length.Equals(0))
            {
                errorProvider.SetError(txt_Status, "cannot be empty");
                filled = false;
            }
            if ((txt_Telephone.Text).Trim().Length.Equals(0))
            {
                errorProvider.SetError(txt_Telephone, "cannot be empty");
                filled = false;
            }
            if ((txt_Cellular.Text).Trim().Length.Equals(0))
            {
                errorProvider.SetError(txt_Cellular, "cannot be empty");
                filled = false;
            }
            if ((txt_Address.Text).Trim().Length.Equals(0))
            {
                errorProvider.SetError(txt_Address, "cannot be empty");
                filled = false;
            }
            if ((txt_Email.Text).Trim().Length.Equals(0))
            {
                errorProvider.SetError(txt_Email, "cannot be empty");
                filled = false;
            }
            if ((rtb_Remarks.Text).Trim().Length.Equals(0))
            {
                errorProvider.SetError(rtb_Remarks, "cannot be empty");
                filled = false;
            }
            if ((pictureBox1.Image.Equals(0)))
            {
                //errorProvider.SetError((pictureBox1.Image.Equals(0)), "cannot be empty");
                filled = false;
            }*/

            if (filled == true)
            {
                array.Insert(0, txt_WorkNumber.Text);
                array.Insert(1, txt_FirstName.Text);
                array.Insert(2, txt_LastName.Text);
                array.Insert(3, txt_BirthDate.Text);
                array.Insert(4, txt_Status.Text);
                array.Insert(5, txt_Telephone.Text);
                array.Insert(6, txt_Cellular.Text);
                array.Insert(7, txt_Address.Text);
                array.Insert(8, txt_Email.Text);
                array.Insert(9, rtb_Remarks.Text);
                array.Insert(10, pictureBox1.Image);

                excel.CreateFile(array);
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Password pas = new Password();
            pas.ShowDialog();
        }

        private void btn_Delete_Click(object sender, EventArgs e)
        {
            try
            {
                //OleDbCommand command = new OleDbCommand();//"Delete * from Users where WorkNumber = " + this.txt_Find.Text, oleDbConnection);
                this.oleDbConnection = new OleDbConnection();

                oleDbConnection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Data\\Users_DB.mdb";
                this.adapter1 = new OleDbDataAdapter();
                 this.adapter1.DeleteCommand.Connection = oleDbConnection;
                this.adapter1.DeleteCommand = new OleDbCommand();                
                this.adapter1.DeleteCommand.CommandText =
                 " [Delete * from Users where WorkNumber =] " + this.txt_Find.Text;
                //open the bridge between the application and the datasource
                this.oleDbConnection.Open();              

                //execute the qurey 
                this.adapter1.DeleteCommand.ExecuteNonQuery();

                //close the connection
                this.oleDbConnection.Close();

                MessageBox.Show("Record deleted Successfully \n \nITEM CLEAR !!!", " Warning !!! Warning !!! Warning !!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);  //inform the user
                this.Close();


            }
            catch (System.Data.OleDb.OleDbException exp)
            {

                MessageBox.Show(exp.ToString());
            }
            finally
            {
                //close the connection
                this.oleDbConnection.Close();
            }


        }

        private void txt_Find_TextChanged(object sender, EventArgs e)
        {
            dataTable.DefaultView.RowFilter = "WorkNumber LIKE '" + txt_Find.Text + "%'";
        }

        private void txt_ID_TextChanged(object sender, EventArgs e)
        {
            dataTable.DefaultView.RowFilter = "UserID LIKE '" + textBox1.Text + "%'";
        }

     }
}

просмотри плиззз,а то я что то :(
Зарание огромное спасибо.
PM MAIL   Вверх
farad
Дата 15.1.2008, 18:36 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Бывалый
*


Профиль
Группа: Участник
Сообщений: 199
Регистрация: 1.11.2007

Репутация: 3
Всего: 6



Первое что увидел: зачем создавать DataSet если в нем одна таблица? Ну ладно, но при это делать адаптером Fill DataSet-у, а нужне тебе опять же таблица. Потом если експерментируешь с разными провадерами, ремаришь их там, зачем сюда выкладывать.. На втором десятке строк ремарок - смотреть надоедает. Кстати можно работать с интерфейсами и инитить их конкретными классами для конкретного провайдера - переносимость повышается..
PM MAIL   Вверх
shark1
Дата 16.1.2008, 09:27 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 274
Регистрация: 10.11.2007

Репутация: нет
Всего: нет



ты прав прошу прощения.вот этот же код вез лишнего


Код

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.IO;

namespace StoreImagesInSQLServer
{
    public partial class frmImagesStore : Form
    {
        private System.Data.DataTable dataTable;        
        public frmImagesStore()
        {
            InitializeComponent();
         }

        void GetImagesFromDatabase()
        {
            
            try
            {
                OleDbConnection conn = new OleDbConnection();
                conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Data\\Users_DB.mdb";
                OleDbDataAdapter adapter = new OleDbDataAdapter("Select * from Users", conn);

               
                DataSet ds = new DataSet();
                dataTable = ds.Tables.Add("Users");

                adapter.Fill(ds, "Users");
                 dataGridView1.DataSource = ds.Tables["Users"];

                
                this.txt_WorkNumber.DataBindings.Add("Text", dataTable, "WorkNumber", true, DataSourceUpdateMode.OnPropertyChanged);
                this.txt_FirstName.DataBindings.Add("Text", dataTable, "FirstName", true, DataSourceUpdateMode.OnPropertyChanged);
                this.txt_LastName.DataBindings.Add("Text", dataTable, "LastName", true, DataSourceUpdateMode.OnPropertyChanged);
                this.txt_BirthDate.DataBindings.Add("Text", dataTable, "BirthDate", true, DataSourceUpdateMode.OnPropertyChanged);
                this.txt_Status.DataBindings.Add("Text", dataTable, "Status", true, DataSourceUpdateMode.OnPropertyChanged);
                this.txt_Telephone.DataBindings.Add("Text", dataTable, "Telephone", true, DataSourceUpdateMode.OnPropertyChanged);
                this.txt_Cellular.DataBindings.Add("Text", dataTable, "Cellular", true, DataSourceUpdateMode.OnPropertyChanged);
                this.txt_Address.DataBindings.Add("Text", dataTable, "Address", true, DataSourceUpdateMode.OnPropertyChanged);
                this.txt_Email.DataBindings.Add("Text", dataTable, "Email", true, DataSourceUpdateMode.OnPropertyChanged);
                this.rtb_Remarks.DataBindings.Add("Text", dataTable, "Remarks", true, DataSourceUpdateMode.OnPropertyChanged);
                this.pictureBox1.DataBindings.Add("Text", dataTable, "Photo", true, DataSourceUpdateMode.OnPropertyChanged);
                


                foreach (DataGridViewColumn column in dataGridView1.Columns) column.SortMode = DataGridViewColumnSortMode.NotSortable;               

              }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void cmdConnect_Click(object sender, EventArgs e)
        {
             GetImagesFromDatabase();
        }

        
        private void cmdStoreNewImage_Click(object sender, EventArgs e)
        {
            frmNewImage fNew = new frmNewImage();
            fNew.txtConnectionString.Text = txtConnectionString.Text;
            fNew.ShowDialog();
        }

        private void dataGridView1_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                byte[] imageData = (byte[])dataGridView1.Rows[e.RowIndex].Cells["Photo"].Value;

               
                Image newImage;
               using (MemoryStream ms = new MemoryStream(imageData, 0, imageData.Length))
                {
                    ms.Write(imageData, 0, imageData.Length);

                    newImage = Image.FromStream(ms, true);
                }
                pictureBox1.Image = newImage;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        

        private void btn_SaveInExcel_Click(object sender, EventArgs e)
        {
            ExcelAuto excel = new ExcelAuto();

            ArrayList array = new ArrayList();
            bool filled = true;

            if (filled == true)
            {
                array.Insert(0, txt_WorkNumber.Text);
                array.Insert(1, txt_FirstName.Text);
                array.Insert(2, txt_LastName.Text);
                array.Insert(3, txt_BirthDate.Text);
                array.Insert(4, txt_Status.Text);
                array.Insert(5, txt_Telephone.Text);
                array.Insert(6, txt_Cellular.Text);
                array.Insert(7, txt_Address.Text);
                array.Insert(8, txt_Email.Text);
                array.Insert(9, rtb_Remarks.Text);
                array.Insert(10, pictureBox1.Image);

                excel.CreateFile(array);
            }
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Password pas = new Password();
            pas.ShowDialog();
        }

        private void btn_Delete_Click(object sender, EventArgs e)
        {
            try
            {
 this.oleDbConnection = new OleDbConnection();

                oleDbConnection.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Data\\Users_DB.mdb";
                this.adapter1 = new OleDbDataAdapter();
                 this.adapter1.DeleteCommand.Connection = oleDbConnection;
                this.adapter1.DeleteCommand = new OleDbCommand();                
                this.adapter1.DeleteCommand.CommandText =
                 " [Delete * from Users where WorkNumber =] " + this.txt_Find.Text;
                this.oleDbConnection.Open();              

              this.adapter1.DeleteCommand.ExecuteNonQuery();

               this.oleDbConnection.Close();

                MessageBox.Show("Record deleted Successfully \n \nITEM CLEAR !!!", " Warning !!! Warning !!! Warning !!!", MessageBoxButtons.OK, MessageBoxIcon.Warning);  //inform the user
                this.Close();


            }
            catch (System.Data.OleDb.OleDbException exp)
            {

                MessageBox.Show(exp.ToString());
            }
            finally
            {
               
                this.oleDbConnection.Close();
            }


        }

        private void txt_Find_TextChanged(object sender, EventArgs e)
        {
            dataTable.DefaultView.RowFilter = "WorkNumber LIKE '" + txt_Find.Text + "%'";
        }

        private void txt_ID_TextChanged(object sender, EventArgs e)
        {
            dataTable.DefaultView.RowFilter = "UserID LIKE '" + textBox1.Text + "%'";
        }

     }
}

но что за причина почему не выполняется Delete.спасибо.
PM MAIL   Вверх
Ответ в темуСоздание новой темы Создание опроса
Прежде чем создать тему, посмотрите сюда:
stab
mr.DUDA
Exception

Используйте теги [code=csharp][/code] для подсветки кода. Используйтe чекбокс "транслит" если у Вас нет русских шрифтов.

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, stab, mr.DUDA, Exception.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Базы данных под .NET | Следующая тема »


 




[ Время генерации скрипта: 0.0688 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.