1
votes

These are my SQL tables CONSTRAINT [FK_regLloji_regModeli] FOREIGN KEY([Shifra_Mod]

This is my combobox values

When i read article 0001 result in Combobox it is OK:

When i try another article like 0002 i see this error:

This is the code i read data from database. I have problem only with Combobox

    private void txtShifra_KeyDown(object sender, KeyEventArgs e)
    {
using (SqlConnection connection = new SqlConnection(connstring))
{
  SqlCommand command1 =
    new SqlCommand("select * from regLloji where Shifra_Lloji = '" + txtShifra.Text + "'", connection);
  connection.Open();

  SqlDataReader read1 = command1.ExecuteReader();

  while (read1.Read())
  {
      txtShifra.Text = (read1["Shifra_Lloji"].ToString());
      txtLloji.Text = (read1["Lloji"].ToString());
      string combobox = (string)(read1["Shifra_Mod"]);
      comboBox1.SelectedValue = combobox;

  }

  read1.Close();
}}

Here is the code to populate the ComboBox:

this.comboBox1.DataBindings.Add(
  new System.Windows.Forms.Binding("SelectedValue", 
  this.regModeliBindingSource, "Shifra_Mod", true));
  this.comboBox1.DataSource = this.regModeliBindingSource;
  this.comboBox1.DisplayMember = "Modeli"; this.comboBox1.ValueMember = "Shifra_Mod"; 

The Style of the ComboBox is set to DropDownList.

FULL Windows Form Code:

using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace PROJECT1
{
    public partial class regLlojet : Form
    {
        public string connstring = @"Data Source=tcp:10.0.0.1;Initial Catalog=Database;User ID=user;Password=pass;MultipleActiveResultSets=true;";
        Timer timer1 = new Timer();
        public regLlojet()
        {
            InitializeComponent();
            if (String.IsNullOrEmpty(txtShifra.Text))
            {
                txtLloji.Enabled = false;
                comboBox1.Enabled = false;
                btnKonfirm.Enabled = false;
                btnDelete.Enabled = false;
            }
            timer1.Interval = 2000; //10 sec interval
            timer1.Tick += new EventHandler(Tick); //Tick event


        }
        private void Tick(object sender, EventArgs e)
        {

            lblRuajtja.Text = "";
            timer1.Stop(); //Stop timer after tick once

        }
        protected override bool ProcessDialogKey(Keys keyData)
        {
            if (Form.ModifierKeys == Keys.None && keyData == Keys.Escape)
            {
                this.Close();
                return true;
            }
            return base.ProcessDialogKey(keyData);
        }
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            //Press Key
            if (keyData == Keys.F2)
            {
                Anulo();
            }
            else if (keyData == Keys.F8)
            {
                btnKonfirm.PerformClick();
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }
        public void Anulo()
        {
            //Clean Textbox
            Action<Control.ControlCollection> func = null;

            func = (controls) =>
            {
                foreach (Control control in controls)
                    if (control is TextBox)
                        (control as TextBox).Clear();
                    else
                        func(control.Controls);
                this.comboBox1.Text = null;

            };

            func(Controls);
            txtLloji.Enabled = false;
            comboBox1.Enabled = false;
            btnKonfirm.Enabled = false;
            btnDelete.Enabled = false;
        }
        private void btnKonfirm_Click(object sender, EventArgs e)
        {
            //Create new user
            if (String.IsNullOrEmpty(txtLloji.Text))
            {
                MessageBox.Show("Plotesoni fushen Lloji", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            }else if (String.IsNullOrEmpty(comboBox1.Text))
            {
                MessageBox.Show("Plotesoni fushen Modeli", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);

            }

            else
            {
                SqlConnection con1 = new SqlConnection(connstring);
                SqlCommand cmd1 = new SqlCommand();
                try
                {
                    if (con1.State == ConnectionState.Closed)
                    {
                        con1.Open();
                    }

                    //Insert Data in Elk_KonfigGrp
                    cmd1 = new SqlCommand("sp_Insert_Lloji", con1);
                    cmd1.Parameters.AddWithValue("@Action", "INSERT");
                    cmd1.CommandType = CommandType.StoredProcedure;
                    cmd1.Parameters.AddWithValue("@Shifra_Lloji", txtShifra.Text);
                    cmd1.Parameters.AddWithValue("@Lloji", txtLloji.Text);
                    cmd1.Parameters.AddWithValue("@Shifra_Mod", comboBox1.SelectedValue);
                    int conn = cmd1.ExecuteNonQuery();
                    if (conn == 0)
                    {
                        //Not updated.
                        lblRuajtja.Text = "Lloji i vetures nuk u ruajt.";
                        timer1.Start(); //start timer  
                    }
                    else
                    {
                        //Updated.
                        lblRuajtja.Text = "Lloji i vetures u ruajt me sukses..";
                        timer1.Start(); //start timer  
                    }
                }
                catch (Exception)
                {// do exception handling here

                    lblRuajtja.Text = "Lloji i vetures nuk u ruajt CATCH.";
                    timer1.Start(); //start timer  
                }
                con1.Close();
                Anulo();
            }
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            //Delete
            SqlConnection con3 = new SqlConnection(connstring);
            SqlCommand cmd3 = new SqlCommand();

            try
            {
                if (con3.State == ConnectionState.Closed)
                {
                    con3.Open();
                }

                {
                    //Delete Data in Elk_KonfigEdin
                    cmd3 = new SqlCommand("sp_Insert_Lloji", con3);
                    cmd3.CommandType = CommandType.StoredProcedure;
                    cmd3.Parameters.AddWithValue("@Action", "DELETE");
                    cmd3.Parameters.AddWithValue("@Shifra_Lloji", txtShifra.Text);
                    cmd3.Parameters.AddWithValue("@Lloji", txtLloji.Text);
                    cmd3.Parameters.AddWithValue("@Shifra_Mod", comboBox1.SelectedValue);


                    int conn3 = cmd3.ExecuteNonQuery();
                    if (conn3 == 0)
                    {
                        //Not updated.
                        lblRuajtja.Text = "Lloji i vetures nuk eshte fshir.";
                        timer1.Start(); //start timer  
                    }
                    else
                    {
                        //Updated.
                        lblRuajtja.Text = "Lloji i vetures eshte fshir me sukses.";
                        timer1.Start(); //start timer  
                    }
                }
            }

            catch (Exception)
            {// do exception handling here

                lblRuajtja.Text = "Lloji i vetures nuk eshte fshir.";
                timer1.Start(); //start timer  
            }
            con3.Close();
            Anulo();
        }

        private void btnAnulo_Click(object sender, EventArgs e)
        {
            Anulo();
        }

        private void btnDalje_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void txtShifra_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)

                if (((TextBox)sender).Text.Length < 5)
                {
                    e.SuppressKeyPress = true;
                    string str = "";
                    int addZeroes = 4 - txtShifra.Text.Length;
                    for (int i = 0; i < addZeroes; i++)
                    {
                        str += "0";
                    }
                    string val = txtShifra.Text;
                    txtShifra.Text = "";
                    txtShifra.Text = str + val;
                    txtLloji.Enabled = true;
                    comboBox1.Enabled = true;
                    txtLloji.Focus();
                    if (txtLloji.Enabled == true)
                    {
                        btnKonfirm.Enabled = true;
                        btnDelete.Enabled = true;
                    }
                    else
                    {
                        btnKonfirm.Enabled = false;
                        btnDelete.Enabled = false;
                    }

                }
                else
                {
                    e.SuppressKeyPress = true;
                    txtLloji.Enabled = true;
                    comboBox1.Enabled = true;
                    txtLloji.Focus();
                    if (txtLloji.Enabled == true)
                    {
                        btnKonfirm.Enabled = true;
                        btnDelete.Enabled = true;
                    }
                    else
                    {
                        btnKonfirm.Enabled = false;
                        btnDelete.Enabled = false;
                    }
                }
            using (SqlConnection connection = new SqlConnection(connstring))
            {
                SqlCommand command1 =
                 new SqlCommand("select * from regLloji where Shifra_Lloji = '" + txtShifra.Text + "'", connection);
                connection.Open();

                SqlDataReader read1 = command1.ExecuteReader();


                while (read1.Read())
                {
                    txtShifra.Text = (read1["Shifra_Lloji"].ToString());
                    txtLloji.Text = (read1["Lloji"].ToString());
                    string combobox = (string)(read1["Shifra_Mod"]);
                    comboBox1.SelectedValue = combobox;
                }
                read1.Close();
            }
        }

        private void txtLloji_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.SuppressKeyPress = true;
                comboBox1.Focus();
            }
        }
        private void comboBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                e.SuppressKeyPress = true;
                btnKonfirm.Focus();
            }
        }

        private void txtShifra_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private void regLlojet_Load(object sender, EventArgs e)
        {
            this.regModeliTableAdapter.Fill(this.modeliVeturesDataSet.regModeli);
            this.comboBox1.Text = null;

        }
    }
}
1
What is "combobox"?Afnan Makhdoom
Its a string read from the line aboveBugFinder
The problem is i want to select the value in combobox as it is in Database i added another post with more pictures because wont allow me to post more than 2 in my original postaarriiaann
Is ComboBox.Style = DropDownList?Vojtěch Dohnal
Are you absolutely sure there is no other event triggered on a change of value in the combobox? The error message as @VojtěchDohnal says is a constraint error, but assigning SelectedValue will not of itself trigger any data changes, unless there is some other event happening as a result.Jonathan Willcock

1 Answers

1
votes

OK found it (I think). The problem is the DataBindings on your combobox

this.comboBox1.DataBindings.Add(
  new System.Windows.Forms.Binding("SelectedValue", 
  this.regModeliBindingSource, "Shifra_Mod", true));

This I am fairly sure is why when the SelectedValue changes, you get an error on your BindingSource.

What is this line supposed to be doing? If you simply delete it, your program will run fine! (Famous last words :-))