My method starts on the second click of the button in C# - c#

What I have is a search button, which connects to the database, but then when I hit search and the txtEstado TextBox is not empty, it should disable the other txtboxes, but it does so when I query with another search, that is to say in the second click, but I need that when the txtbox is with values these are disabled at once, when pressing the search button
'''
private void btnBuscar_Click(object sender, EventArgs e)
{
//metodo buscar
BuscaRegistro(txtCodCli.Text);
}
private void FBorrado()
{
if ( txtEstado.Text != String.Empty)
{
txtNomCli.Enabled = false;
txtApeCli.Enabled = false;
txtDirCli.Enabled = false;
}
else
{
txtNomCli.Enabled = true;
txtApeCli.Enabled = true;
txtDirCli.Enabled = true;
}
}
private bool BuscaRegistro(string codigo)
{
MySqlConnection cn = new MySqlConnection(conexion);
try
{
String CadenaSql = "select nomcli, apecli, dircli, estado from sftclie0 where codcli=" + codigo;
MySqlDataAdapter Adaptador = new MySqlDataAdapter(CadenaSql, cn);
DataSet ds = new DataSet();
cn.Open();
Adaptador.Fill(ds);
cn.Close();
if (ds.Tables[0].Rows.Count == 0)
{
txtNomCli.Text = "";
txtApeCli.Text = "";
txtDirCli.Text = "";
txtEstado.Text = "";
txtNomCli.Focus();
Encontrado = 0;
return false;
}
else
{
txtNomCli.Text = ds.Tables[0].Rows[0]["nomcli"].ToString();
txtApeCli.Text = ds.Tables[0].Rows[0]["apecli"].ToString();
txtDirCli.Text = ds.Tables[0].Rows[0]["dircli"].ToString();
txtEstado.Text = ds.Tables[0].Rows[0]["Estado"].ToString();
txtNomCli.Focus();
Encontrado = 1;
return true;
}
}
catch
{
MessageBox.Show("No pudo conectar a la base de datos");
return false;
}
}
'''
This is the screen
What I want to achieve is the following:
This is what i want to get, but at the first click

Shouldn't you be calling to FBorrado aventually?

Related

c# Windows Form slow rendering objects

I have spent some time designing my first project using C#, it is a Windows form project with 8 buttons on the side. pressing one of the buttons will open another form within the parent form as a window. On clicking the button the new form loads up about 27 objects mostly Labels, Textboxes, Comboboxes and a few DateTimePickers. For some reason it you can see it drawing the boxes and it looks slow. I have an SQL db included with my project which is tiny and contains only 2 rows of data. It is very dishearting to spend all that time working on it only to see it run like a ZX Spectrum. I am using Microsoft Visual Studio 2019 and is fully updated. I have no errors, no warnings thank god but the performance is horrible. One of the comboBoxes when selected will make visible 3 more textBoxes and even making those visible is really slow. Is there something I am doing wrong or is there a way to have it working faster please?
This is the code of my childForm which opens from the main parentForm, sorry is is a bit long but it is all of it.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace AvianManager.Forms
{
public partial class formMyBirds : Form
{
SqlConnection connection = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Dion\Documents\AvianManager.mdf;Integrated Security=True;Connect Timeout=30");
public formMyBirds()
{
InitializeComponent();
}
private void formMyBirds_Load(object sender, EventArgs e)
{
}
private void panel1_Paint(object sender, PaintEventArgs e)
{
}
private void pictureBox1_Click(object sender, EventArgs e)
{
var form = Application.OpenForms["formMyBirdsHelper"]; // Lookup form and check if already open
if (form == null)
{
formMyBirdsHelper MyBirdsHelper = new formMyBirdsHelper(); // Instantiate a FormMyBirdsHelp object.
MyBirdsHelper.Show(); // Show FormMyBirdsHelp and
}
}
private void comboBoxLegBandType_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxLegBandType.GetItemText(this.comboBoxLegBandType.SelectedItem);
if (selected != "None" || selected == null)
{
textBoxLegBandID.Visible = true;
labelLegBandId.Visible = true;
textBoxLegBandSize.Visible = true;
labelLegBandSize.Visible = true;
}
else
{
textBoxLegBandID.Visible = false;
labelLegBandId.Visible = false;
textBoxLegBandSize.Visible = false;
labelLegBandSize.Visible = false;
}
}
private void comboBoxPrevOwner_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxPrevOwner.GetItemText(this.comboBoxPrevOwner.SelectedItem);
if (selected != "No")
{
textBoxLastOwnerName.Visible = true;
labelLastOwnerName.Visible = true;
textBoxLastOwnerFone.Visible = true;
labelLastOwnerFone.Visible = true;
textBoxLastOwnerAddr.Visible = true;
labelLastOwnerAddr.Visible = true;
}
else
{
textBoxLastOwnerName.Visible = false;
labelLastOwnerName.Visible = false;
textBoxLastOwnerFone.Visible = false;
labelLastOwnerFone.Visible = false;
textBoxLastOwnerAddr.Visible = false;
labelLastOwnerAddr.Visible = false;
}
}
private void comboBoxVitalStatus_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxVitalStatus.GetItemText(this.comboBoxVitalStatus.SelectedItem);
if (selected != "Alive")
{
dateTimeDateOfDeath.Visible = true;
labelDateOfDeath.Visible = true;
textBoxCauseOfDeath.Visible = true;
labelCauseOfDeath.Visible = true;
}
else
{
dateTimeDateOfDeath.Visible = false;
labelDateOfDeath.Visible = false;
textBoxCauseOfDeath.Visible = false;
labelCauseOfDeath.Visible = false;
}
}
private void comboBoxRetained_SelectedIndexChanged(object sender, EventArgs e)
{
string selected = this.comboBoxRetained.GetItemText(this.comboBoxRetained.SelectedItem);
if (selected != "Yes")
{
dateTimeRelinquishedDate.Visible = true;
labelRelinquishedDate.Visible = true;
}
else
{
dateTimeRelinquishedDate.Visible = false;
labelRelinquishedDate.Visible = false;
}
}
private void textBoxUid_TextChanged(object sender, EventArgs e)
{
SqlCommand cmd1 = new SqlCommand("select top 1 * from dbMyBirds where db_Uid = '" + textBoxUid.Text + "'", connection);
cmd1.Parameters.AddWithValue("db_Uid", textBoxUid.Text);
SqlDataReader reader1;
connection.Open();
reader1 = cmd1.ExecuteReader();
if (reader1.Read())
{
labelResult.Text = "Found";
textBoxName.Text = reader1["db_Name"].ToString();
textBoxSpecies.Text = reader1["db_Species"].ToString();
comboBoxLegBandType.Text = reader1["db_LegBandType"].ToString();
textBoxLegBandID.Text = reader1["db_LegBandId"].ToString();
textBoxLegBandSize.Text = reader1["db_LegBandSize"].ToString();
comboBoxPrevOwner.Text = reader1["db_PrevOwner"].ToString();
textBoxLastOwnerName.Text = reader1["db_PrevOwnerName"].ToString();
textBoxLastOwnerFone.Text = reader1["db_PrevOwnerFone"].ToString();
textBoxLastOwnerAddr.Text = reader1["db_PrevOwnerAddr"].ToString();
comboBoxIsHybrid.Text = reader1["db_Hybrid"].ToString();
comboBoxRearedBy.Text = reader1["db_RearedBy"].ToString();
textBoxDisformaties.Text = reader1["db_Disformaties"].ToString();
comboBoxVitalStatus.Text = reader1["db_VitalStatus"].ToString();
dateTimeDateOfDeath.Text = reader1["db_DateDied"].ToString();
textBoxCauseOfDeath.Text = reader1["db_CauseOfDeath"].ToString();
comboBoxRetained.Text = reader1["db_Retained"].ToString();
dateTimeRelinquishedDate.Text = reader1["db_RelinquishedDate"].ToString();
dateTimeHatchDate.Text = reader1["db_HatchDate"].ToString();
dateTimeFledgeDate.Text = reader1["db_FledgeDate"].ToString();
comboBoxMaleParentHybrid.Text = reader1["db_MPisHybrid"].ToString();
textBoxMaleParentId.Text = reader1["db_MPUid"].ToString();
textBoxMaleParentSpecies.Text = reader1["db_MPSpecies"].ToString();
comboBoxHenParentHybrid.Text = reader1["db_FPisHybrid"].ToString();
textBoxHenParentId.Text = reader1["db_FPUid"].ToString();
textBoxHenParentSpecies.Text = reader1["db_FPSpecies"].ToString();
textBoxNotes.Text = reader1["db_Notes"].ToString();
}
else
{
resetInputs();
if (textBoxUid.Text == "")
{
labelResult.Text = "Live Search";
}
else
{
labelResult.Text = "Nothing Found";
}
}
connection.Close();
}
//Reset input fields if no results
private void resetInputs()
{
string dt2;
DateTime date2 = DateTime.Now;
dt2 = date2.ToShortDateString(); // display format: 15/07/2021
textBoxName.Text = "";
textBoxSpecies.Text = "";
comboBoxLegBandType.Text = "Select";
textBoxLegBandID.Text = "";
textBoxLegBandSize.Text = "";
comboBoxPrevOwner.Text = "Select";
textBoxLastOwnerName.Text = "";
textBoxLastOwnerFone.Text = "";
textBoxLastOwnerAddr.Text = "";
comboBoxIsHybrid.Text = "Select";
comboBoxRearedBy.Text = "Select";
textBoxDisformaties.Text = "";
comboBoxVitalStatus.Text = "Select";
dateTimeDateOfDeath.Text = dt2;
textBoxCauseOfDeath.Text = "";
comboBoxRetained.Text = "Select";
dateTimeRelinquishedDate.Text = dt2;
dateTimeHatchDate.Text = dt2;
dateTimeFledgeDate.Text = dt2;
comboBoxMaleParentHybrid.Text = "Select";
textBoxMaleParentId.Text = "";
textBoxMaleParentSpecies.Text = "";
comboBoxHenParentHybrid.Text = "Select";
textBoxHenParentId.Text = "";
textBoxHenParentSpecies.Text = "";
textBoxNotes.Text = "";
}
private void buttonInsert_Click(object sender, EventArgs e)
{
}
}
}

How to fix hiding datagridview object

I'm setting datagridview as object and show in windows form in Textbox change event. When open form and start texting into textbox then datagridview is show but when text is empty or null datagridview continue been visible. How can I accomplish datagridview invisible in windows form?
This is for C#. I have tried to dispose datagridview in if clause but it didn't work.
Here is my code:
public class CreateDataGridView
{
public DataGridView clientsDgv = new DataGridView();
public CreateDataGridView()
{
clientsDgv.ReadOnly = true;
clientsDgv.Name = "clientsDgv";
clientsDgv.AllowUserToAddRows = false;
clientsDgv.AllowUserToDeleteRows = false;
clientsDgv.AllowUserToResizeRows = false;
}
public DataGridView Createdgv()
{
return clientsDgv;
}
Here is my code in windows form.
//Get datagridview in windows form textbox change event
private void TxtID_TextChanged(object sender, EventArgs e)
{
switch (this.cmbSelectAction.SelectedIndex)
{
case 1:
CreateDataGridView clientsdgv = new CreateDataGridView();
//clientsdgv.clientsDgv
Controls.Add(clientsdgv.clientsDgv);
clientsdgv.clientsDgv.BringToFront();
DesignDataGridView designdgv = new DesignDataGridView();
designdgv.ClientsDataGridFormatting(clientsdgv.clientsDgv);
designdgv.ClientsDataGridPosition(clientsdgv.clientsDgv, txtID);
//SetDoubleBuffered.SetDoubleBuffering(clientsdgv.clientsDgv, true);
if (string.IsNullOrEmpty(txtID.Text) || txtID.Text == "0")
{
clientsdgv.clientsDgv.DataSource = null;
clientsdgv.clientsDgv.Update();
clientsdgv.clientsDgv.Dispose();
clientsdgv.clientsDgv.Visible = false;
return;
}
else
{
GetSqlData getSqlData = new GetSqlData();
try
{
clientsdgv.clientsDgv.SuspendLayout();
columnName = "PersonalIDBulstat";
ID = txtID.Text;
clientsdgv.clientsDgv.Visible = true;
clientsdgv.clientsDgv.DataSource = getSqlData.SearchClientsInSql(columnName, ID);
clientsdgv.clientsDgv.Update();
clientsdgv.clientsDgv.ResumeLayout();
}
catch
{
title = "Clients";
SetMessageBoxTypes.MessageBoxContactAdminOk(title);
}
}
break;
}
}
Thank you in advance!
It is my working code when form is load where dgvClients is declare as DataGridView:
private void Clients_Load(object sender, EventArgs e)
{
CreateDataGridView clientsdgv = new CreateDataGridView();
dgvClients = clientsdgv.dgvClients;
}
private void TxtID_TextChanged(object sender, EventArgs e)
{
switch (this.cmbSelectAction.SelectedIndex)
{
case 1:
Controls.Add(dgvClients);
dgvClients.BringToFront();
DesignDataGridView designdgv = new DesignDataGridView();
designdgv.ClientsDataGridPosition(dgvClients, this.txtID);
GetSqlData getSqlData = new GetSqlData();
if (string.IsNullOrEmpty(txtID.Text) || txtID.Text == "0")
{
dgvClients.DataSource = null;
dgvClients.Update();
dgvClients.Visible = false;
return;
}
else
{
try
{
dgvClients.SuspendLayout();
columnName = "PersonalIDBulstat";
ID = txtID.Text;
dgvClients.Visible = true;
dgvClients.DataSource = getSqlData.SearchClientsInSql(columnName, ID);
dgvClients.Update();
dgvClients.ResumeLayout();
}
catch
{
title = "Clients";
SetMessageBoxTypes.MessageBoxContactAdminOk(title);
}
}
break;
}
}

My code don't find the datagridview datasource after running another form at the same time

I'm setting a IT project for the school and i got a problem with the datagridview in c# Winform.
I made a first form with a datagridview connected to my db and i want to make a button who can delete a row from the datagridview if needed.
To make sure the client doesn't make a mistake, i create another form where it ask "do you want to delete this row ? (yes/no)", that's a basic form (label + button).
But when i want to close this form, i go to a function in my first datagrid who will initialize this grid from the start of the program and in this code I use Datagridview.DataSource to make a loop.
The problem is marked here, and when I print my DataSource, it print me nothing like there is no DataSource...
Does anyone the reason or how to keep the DataSource from the previous form when you pop's up a new one ?
My code for the initial grid
public void InitDatagrid()
{
//Initialize the tools
CancelMod.Visible = false;
ApplyMod.Visible = false;
Modifie.Visible = true;
Prevbtn.Visible = true;
ClientCommand.Enabled = true;
Client_Pieces.Enabled = true;
Prices.Enabled = true;
PieceCommand.Enabled = true;
Pieces.Enabled = true;
textBox1.Enabled = true;
RowAdd.Visible = false;
RowDelete.Visible = false;
textboxDel.Visible = false;
labelDel.Visible = false;
dataGridView1.EditMode =
DataGridViewEditMode.EditProgrammatically;
textBox1.Text = "";
this.pieceTableAdapter.Fill(this.mykitboxDataSet5.piece);
//Put the color of the columns as white (initial color)
for (var i = 0; i < ((DataTable)dataGridView1.DataSource).Columns.Count; i++)
{
dataGridView1.Columns[i].DefaultCellStyle.BackColor = Color.White;
}
int count = ((DataTable)dataGridView1.DataSource).Columns.Count;
//Put the changed cells color as white (initial color)
if (count == 8)
{
dataGridView2.EditMode =
DataGridViewEditMode.EditProgrammatically;
DeleteCommand.Visible = false;
textBoxDel2.Visible = false;
labelDel2.Visible = false;
for (int i = 0; i < Convert.ToInt32(dataGridView1.Rows.Count.ToString()); i++)
{
//Column = payment_status and command_status
dataGridView1.Rows[i].Cells[6].Style.BackColor = Color.White;
dataGridView1.Rows[i].Cells[7].Style.BackColor = Color.White;
}
}
}
Here is my code for the pop up
public PopUpDel(string codedb, string text, DataGridView ds)
{
this.codedb = codedb;
InitializeComponent();
code.Text = codedb;
label1.Text = text;
Console.WriteLine(ds);
}
private void yes_Click(object sender, EventArgs e)
{
SKGridPage sk = new SKGridPage();
sk.SqlConnection();
MySqlCommand command = conn.CreateCommand();
command.CommandText = string.Format("DELETE FROM piece WHERE code = '{0}'", this.codedb);
Console.WriteLine(command.CommandText);
try
{
conn.Open();
command.ExecuteNonQuery();
}
catch (Exception x)
{
Console.WriteLine(x.Message);
}
conn.Close();
this.Close();
sk.InitDatagrid();
}
private void no_Click(object sender, EventArgs e)
{
this.Close();
}
}

bindlinglist is updated but datagridview is not

I have the following code that I use to update my datagridview:
public readonly BindingList<InventoryTransaction> InventoryTransactions = new BindingList<InventoryTransaction>() { RaiseListChangedEvents = true };
private bool _scanning;
private string _checkData;
public BarCodeForm()
{
InitializeComponent();
barCodeForm_InventoryTransactionBindingSource.DataSource = InventoryTransactions;
panel1.Enabled = false;
_scanning = true;
timer_ScanTimer.Enabled = false;
//InventoryTransactions.AddingNew += InventoryTransactions_AddingNew;
}
private void timer_ScanTimer_Tick(object sender, EventArgs e)
{
panel1.Enabled = true;
label_Message.Text = "Please press ENTER or click RESET to scan again.";
timer_ScanTimer.Enabled = false;
textBox_ModelNumber.Text = _checkData;
textBox_Quantity.Text = "1";
var qry = (from x in InventoryTransactions
where x.ModelNumber == _checkData
select x).FirstOrDefault();
_checkData = string.Empty;
if (qry == null)
{
textBox_Quantity.Focus();
return;
}
qry.Quantity += qry.Quantity;
barCodeForm_InventoryTransactionBindingSource.EndEdit();
panel1.Enabled = false;
_scanning = true;
timer_ScanTimer.Enabled = false;
panel1.Text = "Scan now!";
ResetForm();
}
The problem is that I have updated the quantity of the InventoryTransactions but my datagridview is not updating. Do I have to issue a command of some sort to force the update or to apply the changes?
Thanks!

I want to update only those columns in my database whose textboxes are enabled and keep previous data for those which are disabled?

(http://s14.directupload.net/images/140127/fooispgt.jpg) Link for image
Please view image for more clarification of the problem bcz i know i'm not able to make it more clear to you.
I want to update data for only those columns which are checked by user via checkboxes and those which are left unchecked don't get updated by NULL value....
what i'm thinking is use 511 if....else conditions each for different update query but it's not possible to implement this.
till now the code for update is this:
else if(update_rdbtn.Checked)
{
FileStream fstream = new FileStream(this.imglocation_lbl.Text, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imgbtarray = br.ReadBytes((int)fstream.Length);
SqlConnection con = new SqlConnection("Data Source=JackSparrow-PC\\sqlexpress;Initial Catalog=HCE_DB;Integrated Security=True;Pooling=False");
SqlCommand cmd = new SqlCommand("Update StudentInfo SET Rollno='" + this.rollno_txtbox.Text + "',Student_Name='" + this.studname_txtbox.Text + "',F_name='" + this.fname_txtbox.Text + "',D_O_B='" + this.dob_txtbox.Text + "',Address='" + this.address_txtbox.Text + "',Phone='" + this.phone_txtbox.Text + "',Valid_upto='" + this.validupto_txtbox.Text + "',Image=#IMG,Branch='" + this.branch_txtbox.Text + "' WHERE Rollno='" + this.rollno_txtbox.Text + "';", con);
SqlDataReader myReader;
try
{
con.Open();
cmd.Parameters.Add(new SqlParameter("#IMG", imgbtarray));
myReader = cmd.ExecuteReader();
MessageBox.Show("Data has been updated");
myReader.Close();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Code for radio btn on checked changed:
private void update_rdbtn_CheckedChanged(object sender, EventArgs e)
{
update_grpbox.Enabled = true;
studname_txtbox.Enabled = false;
fname_txtbox.Enabled = false;
dob_txtbox.Enabled = false;
branch_txtbox.Enabled = false;
address_txtbox.Enabled = false;
phone_txtbox.Enabled = false;
validupto_txtbox.Enabled = false;
Browse_btn.Enabled = false;
studname_chkbox.Checked = false;
fname_chkbox.Checked = false;
dob_chkbox.Checked = false;
branch_chkbox.Checked = false;
Address_chkbox.Checked = false;
phone_chkbox.Checked = false;
validupto_chkbox.Checked = false;
Uploadimg_chkbox.Checked = false;
}
Code for check boxes:
private void studname_chkbox_CheckedChanged(object sender, EventArgs e)
{
if (!studname_chkbox.Checked)
{
studname_txtbox.Enabled = false;
}
else
{
studname_txtbox.Enabled = true;
}
}
private void fname_chkbox_CheckedChanged(object sender, EventArgs e)
{
if (!fname_chkbox.Checked)
{
fname_txtbox.Enabled = false;
}
else
{
fname_txtbox.Enabled = true;
}
}
private void dob_chkbox_CheckedChanged(object sender, EventArgs e)
{
if (!dob_chkbox.Checked)
{
dob_txtbox.Enabled = false;
}
else
{
dob_txtbox.Enabled = true;
}
}
private void branch_chkbox_CheckedChanged(object sender, EventArgs e)
{
if (!branch_chkbox.Checked)
{
branch_txtbox.Enabled = false;
}
else
{
branch_txtbox.Enabled = true;
}
}
private void Address_chkbox_CheckedChanged(object sender, EventArgs e)
{
if (!Address_chkbox.Checked)
{
address_txtbox.Enabled = false;
}
else
{
address_txtbox.Enabled = true;
}
}
private void phone_chkbox_CheckedChanged(object sender, EventArgs e)
{
if (!phone_chkbox.Checked)
{
phone_txtbox.Enabled = false;
}
else
{
phone_txtbox.Enabled = true;
}
}
private void validupto_chkbox_CheckedChanged(object sender, EventArgs e)
{
if (!validupto_chkbox.Checked)
{
validupto_txtbox.Enabled = false;
}
else
{
validupto_txtbox.Enabled = true;
}
}
private void Uploadimg_chkbox_CheckedChanged(object sender, EventArgs e)
{
if (!Uploadimg_chkbox.Checked)
{
Browse_btn.Enabled = false;
}
else
{
Browse_btn.Enabled = true;
}
}

Categories