i got a WinForm Project in C# 4.0.
i want to when the user click the button enter then it call onclick event of this button.
my code:
public XtraForm_Main()
{
InitializeComponent();
...
this.AcceptButton = (Button)this.Controls["button_Valider"];
}
private void Main_Load(object sender, EventArgs e)
{
this.AcceptButton = (Button)this.Controls["button_Valider"];
}
private void button_Valider_Click(object sender, EventArgs e)
{
try
{
using (var connectionWrapper = new Connexion())
{
var connectedConnection = connectionWrapper.GetConnected();
string SqlSyntax = "SELECT * FROM ORDRE WHERE REF_EXPED = #REFERENCE";
SqlCommand comm_InsUpt = new SqlCommand(SqlSyntax, connectionWrapper.conn);
comm_InsUpt.Parameters.AddWithValue("#REFERENCE", textEdit_ref.Text);
SqlDataAdapter adapt_SelectAll = new SqlDataAdapter();
adapt_SelectAll.SelectCommand = comm_InsUpt;
DataSet dSet_SelectAll = new DataSet();
adapt_SelectAll.Fill(dSet_SelectAll, "BON_ETIKET");
var xtraReport_Pricipal = new Zebra_Web();
xtraReport_Pricipal.Parameters["Count_Ordre"].Value = 1;
xtraReport_Pricipal.Parameters["IdPacket"].Value = 1;
xtraReport_Pricipal.DataSource = dSet_SelectAll;
xtraReport_Pricipal.DataMember = dSet_SelectAll.Tables[0].TableName;
xtraReport_Pricipal.CreateDocument();
xtraReport_Pricipal.PrintingSystem.ShowMarginsWarning = false;
xtraReport_Pricipal.PrintingSystem.ContinuousPageNumbering = true;
//xtraReport_Pricipal.ShowPreviewDialog();
xtraReport_Pricipal.Print(Properties.Settings.Default.Zebra);
dSet_SelectAll.Dispose();
adapt_SelectAll.Dispose();
}
}
catch (Exception excThrown)
{
throw new Exception(excThrown.Message, excThrown);
}
}
i have tried to put this line:
this.AcceptButton = (Button)this.Controls["button_Valider"];
in constructor and onLoad From event but still not work.
when the user click the button it nothing happen. i have to clic it with the mouse.
You need to set KeyPreview Property of your Form to True.
and then write a KeyDown Event to Handle Enter Key on Form
as Below:
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
button_Valider_Click(sender,e);
}
}
Related
So I am creating forms using Visual Studio .NET.
I am stuck when I try to add tab pages dynamically on a button click which creates a text box in a new tab.
When I create multiple tabs I want to get the data from the text boxes of each newly created tabs and add it to the database. I am having problems as these text boxes have the same name as I create them dynamically. I am new to C# and I need help.
public void add()
{
aa.Add(txt.Text);
var a = 1;
var newTabPage = new TabPage()
{
Text = "Page"
};
txt = new System.Windows.Forms.TextBox();
this.tabControl1.TabPages.Add(newTabPage);
newTabPage.Controls.Add(this.txt);
System.Windows.Forms.Label lbl = new System.Windows.Forms.Label();
newTabPage.Controls.Add(lbl);
lbl.Text = "New";
txt.Name = "Get";
lbl.AutoSize = true;
lbl.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Underline, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
lbl.Location = new System.Drawing.Point(7, 389);
lbl.Name = "label263";
lbl.Size = new System.Drawing.Size(871, 13);
lbl.TabIndex = 317;
lbl.Text = "AA";
newTabPage.Controls.Add(lbl);
}
private void txt_TextChanged(object sender, EventArgs e)
private void button1_Click_1(object sender, EventArgs e)
{
add();
string value = txt.Text;
aa.Add(value);
}
private void saveToolStripMenuItem2_Click(object sender, EventArgs e)
{
SqlCommand command;
string insert1 = #"insert into testing(test) values(#testingt)";
using (SqlConnection conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
for(int i= 0;i<aa.Count;i++)
{
if (aa[i]!= "" && aa[i]!="New Box")
{
command = new SqlCommand(insert1, conn);
command.Parameters.AddWithValue(#"testingt", aa[i]);
command.ExecuteNonQuery();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Maybe you can set the Name property to distinguish them when you create them by creating an increment variable.
int pagecount = 1;
private void btAddtab_Click(object sender, EventArgs e)
{
TabPage tabPage = new TabPage
{
Name = "Tabpage" + pagecount.ToString(),
Text = "Tabpage" + pagecount.ToString()
};
TextBox textBox = new TextBox
{
Name = "TextBox" + pagecount.ToString()
};
tabPage.Controls.Add(textBox);
tabControl1.TabPages.Add(tabPage);
pagecount++;
}
As for how to get the value of the specified TextBox, you can refer to the following code.
private void btGetValue_Click(object sender, EventArgs e)
{
foreach (TabPage page in tabControl1.TabPages)
{
foreach (Control control in page.Controls)
{
// get the first textbox's value
if (control is TextBox && control.Name == "TextBox1")
{
Console.WriteLine(((TextBox)control).Text);
}
}
}
}
I'm creating dynamically generated buttons, and when I click on the button, the Add_Click method doesn't get fired up.
Here is a sample from my code:
protected void SearchRec(object sender, EventArgs e)
{
SearchResultsPanel.Controls.Clear();
string text_to_search = SearchTB.Text;
Friends RecToSearch = new Friends();
List<Friends> ListNFU = DBS.getNonFriendUsers(User.Identity.Name.ToString(), text_to_search);
if (ListNFU.Count != 0)
{
foreach (Friends NFRIndex in ListNFU)
{
string _FriendsOutput = FR_output(NFRIndex);
HyperLink RecHyperLink = new HyperLink();
RecHyperLink.Text = _FriendsOutput;
RecHyperLink.CssClass = "HyperLinkFriends";
RecHyperLink.ID = NFRIndex.UdName;
SearchResultsPanel.Controls.Add(new LiteralControl("<div style='height:32px'>"));
SearchResultsPanel.Controls.Add(RecHyperLink);
Button addUser = new Button();
addUser.CssClass = "ApproveBTN";
addUser.Text = "send";
addUser.Click += new EventHandler(Add_Click);
addUser.ID = NFRIndex.UdName + "3";
SearchResultsPanel.Controls.Add(addUser);
}
}
else
{
Label NoResultsLabel = new Label();
NoResultsLabel.Text = "Nothing is found";
SearchResultsPanel.Controls.Add(NoResultsLabel);
}
SearchResultsPanel.Controls.Add(new LiteralControl("</div>"));
}
private void Add_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
string _tempID = btn.ID;
string id = _tempID.Substring(0, _tempID.LastIndexOf('3'));
DateTime cdate = new DateTime();
cdate = DateTime.Now;
DBS.AddFriend(User.Identity.Name, id, cdate);
btn.Visible = false;
btn.NamingContainer.FindControl(id).Visible = false;
}
Note: I did something very similar on page_load and it does work.
That is because when the page is reloaded, the control is most probably not recreated. That means that the event won't fire indeed.
You need to place this kind of code in the Page_Load so it gets recreated at postback.
I have a windows form with many controls. A tiny part of it is logging in to an SQL server and fetching the list of database names and assigning the collection to a combobox.
private void InitializeComponent()
{
//...
//...
this.ServerTB = new System.Windows.Forms.TextBox();
this.UserNameTB = new System.Windows.Forms.TextBox();
this.PasswordTB = new System.Windows.Forms.TextBox();
//...
//...
this.ServerTB.TextChanged += new System.EventHandler(this.OnSQLServerChanged);
this.UserNameTB.TextChanged += new System.EventHandler(this.OnSQLServerChanged);
this.PasswordTB.TextChanged += new System.EventHandler(this.OnSQLServerChanged);
this.DatabaseCmbBox = new System.Windows.Forms.ComboBox();
//...
//...
this.DatabaseCmbBox.MouseClick += new System.Windows.Forms.MouseEventHandler(this.DatabaseCmbBox_Click);
//....
}
private void DatabaseCmbBox_Click(object sender, MouseEventArgs e)
{
MessageBox.Show(sender.GetType().ToString());
this.Cursor = Cursors.IBeam;
List<string> dbList = new List<string>();
dbList = GetDatabaseList();
DatabaseCmbBox.DataSource = dbList;
DatabaseCmbBox.SelectedIndex = -1;
if (dbList.Count > 0)
{
DatabaseCmbBox.MouseClick -= DatabaseCmbBox_Click;
}
DatabaseCmbBox.Focus();
this.Cursor = Cursors.Default;
}
protected List<string> GetDatabaseList()
{
List<string> list = new List<string>();
string conString = "server=" + ServerTB.Text + ";uid=" + UserNameTB.Text + ";pwd=" + PasswordTB.Text + "; database=master";
try
{
using (SqlConnection con = new SqlConnection(conString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("select name from sys.databases where name not in ('master', 'model', 'tempdb', 'msdb') ", con))
{
using (IDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
list.Add(dr[0].ToString());
}
dr.Close();
}
cmd.Dispose();
}
con.Close();
}
}
catch(SqlException ex)
{
DatabaseCmbBox.MouseClick -= DatabaseCmbBox_Click;
MessageBox.Show(ex.Message);
ServerTB.Focus();
}
return list;
}
private void OnSQLServerChanged(object sender, EventArgs e)
{
DatabaseCmbBox.MouseClick += DatabaseCmbBox_Click;
}
I don't have a problem in fetching the list of Databases. It takes about 10 seconds to do so. With the messagebox in the event handler, I found out that the MouseClick event, for no apparent reason, gets fired like 38 times. The same thing happens even if I use the Enter event or Click event, instead of the MouseClick event.
Why does this happen, and how does one go about using these kind of events?
Thanks in advance,
RPS.
If you want to get list of Databases, why don't you do so on Combobox value changed event?
Anyways,I see that you are doing
private void OnSQLServerChanged(object sender, EventArgs e)
{
DatabaseCmbBox.MouseClick += DatabaseCmbBox_Click;
}
This should solve your problem
private void OnSQLServerChanged(object sender, EventArgs e)
{
DatabaseCmbBox.MouseClick -= DatabaseCmbBox_Click;
DatabaseCmbBox.MouseClick += DatabaseCmbBox_Click;
}
This is a potential error: you should subscribe DatabaseCmbBox.MouseClick only once, not every time OnSQLServerChanged. Correct your code correspondingly, and the issue with multiple click events will be fixed:
private void OnSQLServerChanged(object sender, EventArgs e)
{
DatabaseCmbBox.MouseClick += DatabaseCmbBox_Click;
}
I have been looking all over the Internet for this and have found similar, but none of it will work for me. Everything I have found assumes the listbox is on the main form and not the secondary form, or the code is for an older version of C# or Visual Studio (I am using VS2008).
I am creating a web browser that has a button on the main form (called frmMyBrowser) to open a dialog (frmBookmarks) with a listbox (lstBookmark) with bookmarked URLs. I need to be able to double click on an item (the bookmarked URL) and have the text pasted into the address bar (cmbAddress) of the main form.
Any help would be GREATLY appreciated.
I figured out that if I create the window at runtime, I can get it to work. In case anyone is interested, the code I used is below.
public void frmMyBrowser_ShowFavorites(object sender, EventArgs e)
{
frmFavorites.ShowIcon = false;
frmFavorites.ShowInTaskbar = false;
frmFavorites.MinimizeBox = false;
frmFavorites.MaximizeBox = false;
frmFavorites.ControlBox = false;
frmFavorites.Text = "Bookmarks";
frmFavorites.Width = 500;
frmFavorites.Height = 350;
frmFavorites.Controls.Add(lstFavorites);
frmFavorites.Controls.Add(btnRemoveFavorite);
frmFavorites.Controls.Add(btnAddFavorite);
frmFavorites.Controls.Add(btnCloseFavorites);
frmFavorites.Controls.Add(txtCurrentUrl);
lstFavorites.Width = 484;
lstFavorites.Height = 245;
btnRemoveFavorite.Location = new Point(8, 280);
btnAddFavorite.Location = new Point(8, 255);
btnCloseFavorites.Location = new Point(400, 255);
txtCurrentUrl.Location = new Point(110, 255);
txtCurrentUrl.Size = new Size(255, 20);
btnAddFavorite.Text = "Add";
btnRemoveFavorite.Text = "Remove";
btnCloseFavorites.Text = "Close";
txtCurrentUrl.Text = wbBrowser.Url.ToString();
btnAddFavorite.Click += new EventHandler(btnAddFavorite_Click);
btnRemoveFavorite.Click += new EventHandler(btnRemoveFavorite_Click);
frmFavorites.Load += new EventHandler(frmFavorites_Load);
btnCloseFavorites.Click += new EventHandler(btnCloseFavorites_Click);
lstFavorites.MouseDoubleClick += new MouseEventHandler(lstFavorites_MouseDoubleClick);
frmFavorites.Show();
}
public void btnCloseFavorites_Click(object sender, EventArgs e)
{
if (lstFavorites.Items.Count > 0)
{
using (StreamWriter writer = new System.IO.StreamWriter(#Application.StartupPath + "\\favorites.txt"))
{
for (int i = 0; i < lstFavorites.Items.Count; i++)
{
writer.WriteLine(lstFavorites.Items[i].ToString());
}
writer.Close();
}
}
frmFavorites.Hide();
}
public void btnAddFavorite_Click(object sender, EventArgs e)
{
string strFavoriteAddress = wbBrowser.Url.ToString();
if (!lstFavorites.Items.Contains(strFavoriteAddress))
{
lstFavorites.Items.Add(strFavoriteAddress);
MessageBox.Show("Favorite Added", "Message");
}
else if (lstFavorites.Items.Contains(strFavoriteAddress))
{
MessageBox.Show("This site already exists in your Favorites list!", "Error");
}
else
{
}
}
public void btnRemoveFavorite_Click(object sender, EventArgs e)
{
try
{
lstFavorites.Items.RemoveAt(lstFavorites.SelectedIndices[0]);
}
catch
{
MessageBox.Show("You need to select an item", "Error");
}
}
public void frmFavorites_Load(object sender, EventArgs e)
{
try
{
using (StreamReader reader = new System.IO.StreamReader(#Application.StartupPath + "\\favorites.txt"))
{
while (!reader.EndOfStream)
{
for (int i = 0; i < 4; i++)
{
string strListItem = reader.ReadLine();
if (!String.IsNullOrEmpty(strListItem))
{
lstFavorites.Items.Add(strListItem);
}
}
}
reader.Close();
}
}
catch
{
MessageBox.Show("An error has occured", "Error");
}
}
private void lstFavorites_MouseDoubleClick(object sender, MouseEventArgs e)
{
string strSelectedAddress = lstFavorites.Text.ToString();
cmbAddress.Text = strSelectedAddress;
wbBrowser.Navigate(strSelectedAddress);
frmFavorites.Hide();
}
Im adding objects to a datagridview ( only one kind) through a list
ej.
List<Material> mater = new List<Material>();
DataGridView dgvMAterial = new DataGridView();
dgvMaterial.DataSource = null;
mater.Add((Material)cmbMaterial.SelectedValue);
dgvMaterial.DataSource = mater;
But every time I click over the datagrid I get an indexoutofrangeexeption.
Can somone tell me why?
thanks
here is my whole code for the form
public partial class inicio : Form
{
private string ConnectionString = "Data Source=localhost\\sqlexpress;Initial Catalog=data.mdf;Integrated Security=SSPI;";
//private string ConnectionString = "Server=.\\SQLExpress;AttachDbFilename=|DataDirectory|\\data\\data_data.mdf.mdf; Database=data.mdf;Trusted_Connection=Yes;";
private ISessionFactory sessionFactory;
List<Material> mater = new List<Material>();
List<Salarios> salar = new List<Salarios>();
IBindingList mind = new BindingList<Salarios>();
Productos prod;
public inicio()
{
InitializeComponent();
sessionFactory = nhn.BusinessObjects.Initialize.CreateSessionFactory(ConnectionString);
dgvMaterial.DataSource = mater;
}
private void materialToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmMaterial material = new costeos.Catalogos.frmMaterial(ConnectionString);
material.ShowDialog(this);
material.Dispose();
}
private void salariosToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmSalarios salarios = new costeos.Catalogos.frmSalarios(ConnectionString);
salarios.ShowDialog(this);
salarios.Dispose();
}
private void agregarToolStripMenuItem_Click(object sender, EventArgs e)
{
Catalogos.frmAddRemuneraciones rem = new costeos.Catalogos.frmAddRemuneraciones(ConnectionString);
rem.ShowDialog(this);
rem.Dispose();
}
private void agregarToolStripMenuItem1_Click(object sender, EventArgs e)
{
Catalogos.frmAddAdmin adm = new costeos.Catalogos.frmAddAdmin(ConnectionString);
adm.ShowDialog(this);
adm.Dispose();
}
private void agregarToolStripMenuItem2_Click(object sender, EventArgs e)
{
Catalogos.frmAddInsumosInd insumos = new costeos.Catalogos.frmAddInsumosInd(ConnectionString);
insumos.ShowDialog(this);
insumos.Dispose();
}
private void txt_KeyPress(object sender, KeyPressEventArgs e)
{
if (char.IsDigit(e.KeyChar) || char.IsPunctuation(e.KeyChar) || char.IsControl(e.KeyChar))
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
private void inicio_Load(object sender, EventArgs e)
{
LlenaCampos();
}
private void LlenaCampos()
{
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var mat = session.CreateCriteria(typeof(Material))
.List<Material>();
var sal = session.CreateCriteria(typeof(Salarios))
.List<Salarios>();
transaction.Commit();
cmbMaterial.DataSource = mat;
cmbMaterial.DisplayMember = "Nombre";
cmbSalarios.DataSource = sal;
cmbSalarios.DisplayMember = "Nombre";
cmbMIndirecta.DataSource = sal;
cmbMIndirecta.DisplayMember = "Nombre";
}
}
}
private void btnAddMaterial_Click(object sender, EventArgs e)
{
materialBindingSource.DataSource = null;
//dgvMaterial.DataSource = null;
mater.Add((Material)cmbMaterial.SelectedValue);
//dgvMaterial.DataSource = mater;
dgvMaterial.DataSource = materialBindingSource;
materialBindingSource.DataSource = mater;
materialBindingSource.ResetBindings(false);
}
private void button2_Click(object sender, EventArgs e)
{
dgvSalarios.DataSource = null;
salar.Add((Salarios)cmbSalarios.SelectedValue);
dgvSalarios.DataSource = salar;
}
private void button3_Click(object sender, EventArgs e)
{
dgvMIndirecta.DataSource = null;
mind.Add((Salarios)cmbMIndirecta.SelectedValue);
dgvMIndirecta.DataSource = mind;
}
private void button1_Click(object sender, EventArgs e)
{
using (var session = sessionFactory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
if (prod == null)
{
prod = new Productos { CargasTurno = float.Parse(txtCargasTurno.Text), CavidadesMolde = int.Parse(txtCavidadesMolde.Text), Clave = txtClave.Text, Comentarios = txtComentarios.Text, MezclasTurno = float.Parse(txtMezclasTurno.Text), Moldes = int.Parse(txtMoldes.Text), Nombre = txtNombre.Text, Peso = float.Parse(txtPesoTotal.Text), TotalPza = int.Parse(txtPzasTotales.Text), Turnos = int.Parse(txtTurnos.Text) };
session.Save(prod);
transaction.Commit();
}
foreach (DataGridViewRow dr in dgvMaterial.Rows)
{
Material m = dr.DataBoundItem as Material;
m.Materiales
PMaterial mat = new PMaterial { Material = dr.DataBoundItem as Material, Cantidad = float.Parse(dr.Cells["Cantidad"].Value.ToString()), Fecha = DateTime.Now, Producto = prod };
session.Save(mat);
}
transaction.Commit();
session.Close();
}
}
}
}
}
That's probably not DGV problem, but with this combo box. Show us the code that fills combo box and sets its properties.
If you are casting to Material class you should probably use SelectedItem instead of SelectedValue. (unless you exactly know what you're doing)
I would guess that you have an event-handler that isn't happy. What exactly does the message say?
You might also be having problems if you are adding the same Material instance to the list multiple times; since IndexOf will only find the first occurrence. This line makes me very suspicious:
mater.Add((Material)cmbMaterial.SelectedValue);
since it could potentially (on consecutive clicks / etc) do exactly this.
Note: if you used BindingList<T> instead all you'd have to doo is Add(...) - no resetting required:
field:
BindingList<Material> mater = new BindingList<Material>();
init grid:
dgvMaterial.DataSource = mater;
add item:
mater.Add(newInstance);
If you assign data source to the DGV you should check element count - if zero then assign null. I don't know why this is the way it is, but I'm doing it in all my forms.
//I'm still analysing the rest of the code