c# Windows Form slow rendering objects - c#

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)
{
}
}
}

Related

My method starts on the second click of the button in 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?

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;
}
}

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!

Web form is not updating values

I am trying to save retrieve and update data table from s single web form. Data is saved and retrieve correctly but is not updated.
Here is the code
using System;
using System.Web.UI;
using System.Data;
public partial class Basic_Information : System.Web.UI.Page
{
DataTable user_dt, personal_dt = new DataTable();
string u_id;
Boolean check = false;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
if (Session["user"] != null)
load();
}
protected void btn_save_Click(object sender, EventArgs e)
{
if(check == false)
savedata();
else
editdata();
}
protected void load()
{
user_dt = (DataTable)Session["user"];
u_id = user_dt.Rows[0][0].ToString();
personal_dt = (DataTable)Session["personal"];
if (personal_dt.Rows.Count != 0)
{
retrivedata();
check = true;
}
}
protected void savedata()
{
personal_dt.Columns.Add("User_id");
personal_dt.Columns.Add("Name");
personal_dt.Columns.Add("Father_Name");
personal_dt.Columns.Add("CNIC");
personal_dt.Columns.Add("Date_of_Birth");
personal_dt.Columns.Add("Domicile");
personal_dt.Columns.Add("Gender");
personal_dt.Columns.Add("Religion");
personal_dt.Columns.Add("Nationality");
personal_dt.Columns.Add("Marital");
DataRow per_row = personal_dt.NewRow();
per_row["User_id"] = u_id;
per_row["Name"] = txt_name.Text;
per_row["Father_Name"] = txt_fname.Text;
per_row["CNIC"] = txt_cnic.Text;
per_row["Date_of_Birth"] = txt_dofb.Text;
per_row["Domicile"] = ddl_domicil.SelectedItem.Text;
per_row["Gender"] = ddl_gender.SelectedItem.Text;
per_row["Religion"] = ddl_religion.SelectedItem.Text;
per_row["Nationality"] = txt_nationality.Text;
per_row["Marital"] = ddl_marital.SelectedItem.Text;
personal_dt.Rows.Add(per_row);
string script = "alert('Profile Successfully Saved');";
ClientScript.RegisterStartupScript(this.GetType(), "saved", script, true);
}
}
protected void retrivedata()
{
txt_name.Text = personal_dt.Rows[0]["Name"].ToString();
txt_fname.Text = personal_dt.Rows[0]["Father_Name"].ToString();
txt_cnic.Text = personal_dt.Rows[0]["CNIC"].ToString();
txt_dofb.Text = personal_dt.Rows[0]["Date_of_Birth"].ToString();
ddl_domicil.Items.FindByText(personal_dt.Rows[0] ["Domicile"].ToString()).Selected = true;
ddl_gender.Items.FindByText(personal_dt.Rows[0]["Gender"].ToString()).Selected = true;
ddl_religion.Items.FindByText(personal_dt.Rows[0]["Religion"].ToString()).Selected = true;
txt_nationality.Text = personal_dt.Rows[0]["Nationality"].ToString();
ddl_marital.Items.FindByText(personal_dt.Rows[0]["Marital"].ToString()).Selected = true;
}
protected void editdata()
{
personal_dt.Rows[0]["Name"] = txt_name.Text;
personal_dt.Rows[0]["Father_Name"] = txt_fname.Text;
personal_dt.Rows[0]["CNIC"] = txt_cnic.Text;
personal_dt.Rows[0]["Date_of_Birth"] = txt_dofb.Text;
personal_dt.Rows[0]["Domicile"] = ddl_domicil.SelectedItem.Text;
personal_dt.Rows[0]["Gender"] = ddl_gender.SelectedItem.Text;
personal_dt.Rows[0]["Religion"] = ddl_religion.SelectedItem.Text;
personal_dt.Rows[0]["Nationality"] = txt_nationality.Text;
personal_dt.Rows[0]["Marital"] = ddl_marital.SelectedItem.Text;
}
}
Saving data correctly, retrieving data correctly.
But bug in editing data return the first values which are retrieved.
Also an error that Dropdown cannot select multiple items
Regarding dropdown binding issue, before
Dropdown.DataSource = YourDataSource
add
Dropdown.ClearSelection();
Try this.After filling data to datatable you need to pass that datatable, and update record.
protected void editdata()
{
DataRow dr = personal_dt.NewRow();
personal_dt.Rows.Add(dr);
dr["Name"] = txt_name.Text;
dr["Father_Name"] = txt_fname.Text;
dr["CNIC"] = txt_cnic.Text;
dr["Date_of_Birth"] = txt_dofb.Text;
dr["Domicile"] = ddl_domicil.SelectedItem.Text;
dr["Gender"] = ddl_gender.SelectedItem.Text;
dr["Religion"] = ddl_religion.SelectedItem.Text;
dr["Nationality"] = txt_nationality.Text;
dr["Marital"] = ddl_marital.SelectedItem.Text;
}

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