So I am developing an application in WinForms and I am populating data from an Access database into a Combobox. After populating it I will use the items from the Combobox to display data on my labels. This is what I have to populate data:
public void AutoCompleteBrand()
{
OleDbConnection con = new OleDbConnection(cs.DBConn);
con.Open();
adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand(#"SELECT DISTINCT RTRIM(Phone) FROM tblPhone", con);
ds = new DataSet("ds");
adapter.Fill(ds);
dtable = ds.Tables[0];
cmbPhone.Items.Clear();
foreach (DataRow drow in dtable.Rows)
{
cmbPhone.Items.Add(drow[0].ToString());
}
}
Then inside of Combobox selected index event I will use this code:
private void cmbPhone_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
OleDbConnection con = new OleDbConnection(cs.DBConn);
con.Open();
cmd = new OleDbCommand(#"SELECT DISTINCT
Brand, Phone, Tecnology
FROM tblPhone", con);
OleDbDataAdapter mAdapter = new OleDbDataAdapter(cmd);
DataSet mDataSet = new DataSet();
OleDbDataReader mReader;
mReader = cmd.ExecuteReader();
while (mReader.Read())
{
string sBrand = mReader.GetString(0);
string sPhone = mReader.GetString(1);
string sTec = mReader.GetString(2);
lblBrand.Text = sBrand;
lblPhone.Text = sPhone;
lblTec.Text = sTec;
}
}
catch (Exception ex)
{
MessageBox.Show("Erro\nDetalhes: " + ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Basically the technology label is too big and when it reaches a length changes line. It is doable?
you just need to set two properties to your label: AutoSize and MaximumSize. AutoSizetells label to grow (both horizontally and vertically) but MaximumSize limits it to certain Width and Height. So. just do something like this:
label1.AutoSize = true;
label1.MaximumSize = new Size(100, 600);
label1.Text = "test string which is pretty long";
Your question is not very clear. You are working with WPF or Winforms ?
Basicly you can try a few things like :
-If winforms, you can set the autosize property = true of your label.
you can try Something like this :
while (mReader.Read())
{
string sBrand = mReader.GetString(0);
string sPhone = mReader.GetString(1);
string sTec = mReader.GetString(2);
lblBrand.Text = sBrand;
lblPhone.Text = sPhone;
lblTec.Text = sTec;
int wdth = sTec.Length * 16; //you can put another value depending your charachter size.
lblTech.Size = new Size(wdth, 22);
}
Or if you can give a fix width to your label and you can check the length of your string to add a new line :
int lngth = 100;
if(sTech.Length > lngth)
{
sTech = sTech.SubString(0, lngth) + Environment.NewLine + sTech.SubString(lngth);
lblTech.Text = sTech;
}
Tell me if it works.
Related
I'm trying to convert data to RichTextBox but still can't do it. Below is my code. My data test and have data, now just read it into RichTextBox.
private void btnConvert_Click(object sender, EventArgs e)
{
ListViewItem selectedComune = lvResultCommune.SelectedItems[0];
string selectedCommuneId = selectedComune.Text;
if (selectedCommuneId != null)
{
NpgsqlDataAdapter adapter = new NpgsqlDataAdapter();
NpgsqlCommand cmd = new NpgsqlCommand("SELECT ST_AsText(geom) as geometry FROM hanhchinhxa where id_4 = " + selectedCommuneId , conn);
adapter.SelectCommand = cmd;
cmd.Connection = conn;
DataTable data = new DataTable();
adapter.Fill(data);
richTextBox.Text = data.ToString();
}
else
{
throw new Exception("\n" + "Geometry illegal !!");
}
}
I found the answer by myself !
richTextBox.Text = data.Rows[0].ItemArray[0].ToString();
I have this code to receive a number from user through a text box, then use that value and two values from a SQL table and perform a simple calculation. I debugged and get no errors but my label in gridview does not populate. Any help would be greatly appreciated.
protected void Calculate_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("SELECT [Divide], [Calc] FROM [Parrts] WHERE (([Region] = 'East Coast') AND ([Model] = #Model) AND ([SashSize] = #SashSize) AND ([Operation] = #Operation) AND ([PartDesc] = #PartDesc) AND ([Description] = #Description) AND ([Lites] =#Lites))", conn);
SqlParameter Model = new SqlParameter("#Model", ddModel.SelectedValue);
cmd.Parameters.Add(Model);
SqlParameter SashSize = new SqlParameter("#SashSize", ddSashSize.SelectedValue);
cmd.Parameters.Add(SashSize);
SqlParameter Operation = new SqlParameter("#Operation", ddOperation.SelectedValue);
cmd.Parameters.Add(Operation);
SqlParameter Part = new SqlParameter("#PartDesc", ddPart.SelectedValue);
cmd.Parameters.Add(Part);
SqlParameter Color = new SqlParameter("#Description",ddColor.SelectedValue);
cmd.Parameters.Add(Color);
SqlParameter Lites = new SqlParameter("#Lites",ddLites.SelectedValue);
cmd.Parameters.Add(Lites);
conn.Open();
cmd.Connection = conn;
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Int32 Divide = (int)rdr["Divide"];
double Calc = (double)rdr["Calc"];
int HW = Convert.ToInt32(length_txt.Text);
foreach (GridViewRow row in GridViewAMI.Rows)
{
string Length = ((Label)row.FindControl("Length")).Text;
Response.Write(Length);
Length = ((HW / Divide) - Calc).ToString();
}
}
rdr.Close();
cmd.Dispose();
conn.Close();
}
Since I can't see you populating the Label again maybe this helps:
foreach (GridViewRow row in GridViewAMI.Rows)
{
// Get the Label safely so you can manipulate it later
Label rowLabel = row.FindControl("Length") as Label;
// If you - for whatever reason - can't get the Label, skip this row
if(rowlabel == null)
continue;
string length = rowLabel.Text;
Response.Write(length);
length = ((HW / Divide) - Calc).ToString();
// Populate the Label with the new Data
rowLabel.Text = length;
}
Try this:
foreach (GridViewRow row in GridViewAMI.Rows)
{
Label lbl = (Label)row.FindControl("Length");
string length = lbl.Text;
Response.Write(length);
length = ((HW / Divide) - Calc).ToString();
lbl.Text = length;
}
You forgot to put the text back in the Label.
i have a datagridview which loads mysql database table t_pi_clients on form load event,and i have another tab which contains textboxes of the respective columns of t_pi_client, which am able to get data from fullrowselect mode into those textboxes. now i want to update the database upon changes in the those textbox values. so far i've tried some process and gets my "entry saved" messageBox.show but nothing happens to database, so am hoping someone could help me out maybe am missing something thanks
public partial class frmMain : Form
{
MySqlConnection connection;
MySqlDataAdapter mySqlDataAdapter;
DataSet dt = new DataSet();
DataSet DS = new DataSet();
DataSet dg = new DataSet();
public frmMain()
{
InitializeComponent();
}
#region Main load
private void frmMain_Load(object sender, EventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["Pigen"].ConnectionString;
connection = new MySqlConnection(connectionString);
if (this.OpenConnection() == true)
{
mySqlDataAdapter = new MySqlDataAdapter("select * from t_pi_Clients", connection);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
kryptonDataGridView1.DataSource = DS.Tables[0];
kryptonDataGridView1.Columns[0].Visible = false;
mySqlDataAdapter = new MySqlDataAdapter("select * from t_pi_msg_charge_Rate", connection);
DataSet dt = new DataSet();
mySqlDataAdapter.Fill(dt);
kryptonDataGridView2.DataSource = dt.Tables[0];
mySqlDataAdapter = new MySqlDataAdapter("select * from t_pi_client_deposits", connection);
DataSet dg = new DataSet();
mySqlDataAdapter.Fill(dg);
kryptonDataGridView3.DataSource = dg.Tables[0];
}
}
//loads selected row data into textboxes
private void kryptonDataGridView1_DoubleClick(object sender, EventArgs e)
{
textboxClientCode.Text = kryptonDataGridView1.SelectedRows[0].Cells["ClientCode"].Value.ToString();
txtboxClientName.Text = kryptonDataGridView1.SelectedRows[0].Cells["ClientName"].Value.ToString();
txtboxPostalAddress.Text = kryptonDataGridView1.SelectedRows[0].Cells["PostalAdd"].Value.ToString();
txtboxTelephone.Text = kryptonDataGridView1.SelectedRows[0].Cells["Telephone"].Value.ToString();
txtboxFax.Text = kryptonDataGridView1.SelectedRows[0].Cells["Fax"].Value.ToString();
txtboxEmailAddress1.Text = kryptonDataGridView1.SelectedRows[0].Cells["EmailAdd1"].Value.ToString();
txtboxEmailAddress2.Text = kryptonDataGridView1.SelectedRows[0].Cells["EmailAdd2"].Value.ToString();
txtboxEmailAddress3.Text = kryptonDataGridView1.SelectedRows[0].Cells["EmailAdd3"].Value.ToString();
txtboxWebsite.Text = kryptonDataGridView1.SelectedRows[0].Cells["Website"].Value.ToString();
txtboxChargeRate.Text = kryptonDataGridView1.SelectedRows[0].Cells["ChargeRate"].Value.ToString();
txtboxTotalDepo.Text = kryptonDataGridView1.SelectedRows[0].Cells["TotalDeposit"].Value.ToString();
txtboxAccountBal.Text = kryptonDataGridView1.SelectedRows[0].Cells["AccountBal"].Value.ToString();
txtboxEntrydate.Text = kryptonDataGridView1.SelectedRows[0].Cells["EntryDate"].Value.ToString();
}
now i tried this method to update but doesn't update database
private void kryptonbtnUpdate_Click(object sender, EventArgs e)
{
var connectionString = ConfigurationManager.ConnectionStrings["Pigen"].ConnectionString;
using (MySqlConnection Conn = new MySqlConnection(connectionString))
if (Conn.State.ToString() != "Open")
{
}
else
{
connection.Open();
}
try
{
DataTable changes = ((DataTable)kryptonDataGridView1.DataSource).GetChanges();
if (changes != null)
{
MySqlCommandBuilder mcb = new MySqlCommandBuilder(mySqlDataAdapter);
mySqlDataAdapter.UpdateCommand = mcb.GetUpdateCommand();
mySqlDataAdapter.Update(changes);
((DataTable)kryptonDataGridView1.DataSource).AcceptChanges();
mySqlDataAdapter.Update(DS);
}
// adapter.Update(rowsToUpdate);
// mySqlDataAdapter.Update(DS);
MessageBox.Show("Entry Saved");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This is just a pseudocode of what you need to do
string cmdText = #"UPDATE t_pi_Clients
SET ClientName = #ClientName,
PostalAdd = #PostalAdd,
Telephone = #Telephone,
Fax = #Fax,
.... etc ....
WHERE ClientCode = #ClientCode";
using(MySqlConnection cn = new MySqlConnection(.....))
using(MySqlCommand cmd = new MySqlCommand(cmdText, cn))
{
cn.Open();
cmd.Parameters.AddWithValue("#ClientName", txtboxClientName.Text);
cmd.Parameters.AddWithValue("#PostalAdd", txtboxPostalAddress.Text);
....etc etc...
cmd.Parameters.AddWithValue("#ClientCode", textboxClientCode.Text);
int rowsUpdated = cmd.ExecuteNonQuery();
if(rowsUpdated > 0)
{
// extract the code that loads DataGridView1 from the Form_Load
// and create a reusable method that you could call from here
}
}
First you build an sql command text with the UPDATE clause. I assume that your primary key (the field that uniquely identifies your records) is the ClientCode field.
Then create the connection and the command. Fill the command parameters collection with the parameters required by your text taking the values from the TextBoxes.
Call the ExecuteNonQuery to store the values.
If you succeed then you need to update or reload your datagridview. The best approach would be setting one by one the gridview cells of the current row with the new values from the textboxes, or you could simply extract the code used in form_load to fill the grid and make a new method that you could call from the button click event. (But this could be slower if you have many records)
I am trying to a get the Row values from a excel sheet, based on the column Value.
e.g. I have CutsomerID as lets say 5 , so I want First name 5, last Name 5 and Address 5
I am converting whole excel sheet into DataTable and then trying to read on each DataRow, when I get CustomerID as 5, I copy all the values and break from the loop
Here is my code and it is working fine as well, but I was wondering is there any way to optimise it.
Here is my Code.
public ExcelData GetDataByCustomerID(String excelFilePath, String customerID)
{
OleDbConnectionStringBuilder connectionStringBuilder = new OleDbConnectionStringBuilder();
connectionStringBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
connectionStringBuilder.DataSource = excelFilePath;
connectionStringBuilder.Add("Mode", "Read");
const string extendedProperties = "Excel 12.0;IMEX=1;HDR=YES";
connectionStringBuilder.Add("Extended Properties", extendedProperties);
String connectionString = connectionStringBuilder.ToString();
// Create connection object by using the preceding connection string.
using( var objConn = new OleDbConnection(connectionString))
{
objConn.Open();
// Get the data table contaning the schema guid.
DataTable excelSheetsDataTable = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (excelSheetsDataTable == null)
return null;
// get all the tables in the Sheet
List<String> excelSheets = (from DataRow row in excelSheetsDataTable.Rows select row["TABLE_NAME"].ToString()).ToList();
// Our data is on First sheet only
OleDbCommand _oleCmdSelect = new OleDbCommand(#"SELECT * FROM [" + excelSheets[0] + "]", objConn);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
oleAdapter.SelectCommand = _oleCmdSelect;
DataTable newDataTable = new DataTable();
oleAdapter.FillSchema(newDataTable, SchemaType.Source);
oleAdapter.Fill(newDataTable);
if (newDataTable.Columns.Contains("CustomerID"))
{
foreach (DataRow rowValue in newTB.Rows)
{
if ((string) rowValue["CustomerID"] == customerID)
{
var data = new ExcelData
{
customerFirstName = rowValue["Customer_First_ Name"].ToString(),
customerLastName = rowValue["Customer_Last_Name"].ToString(),
customerAddress = rowValue["Customer_Address"].ToString(),
};
return data;
}
}
String message = String.Format("The CustomerID {0} not found in Excel file {1}", customerID, excelFilePath);
MessageBox.Show(message);
}
else
{
String message = String.Format("The Column CustomerID not found in Excel file {0}", excelFilePath);
MessageBox.Show(message);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return null;
}
public class ExcelData
{
public String customerID;
public String customerFirstName;
public String customerLastName;
public String customerAddress;
}
Change your select query to like below -
#"SELECT * FROM [" + excelSheets[0] + "] WHERE CustomerID=<your_value>"
Courtesy msdn web site:
Link: MSDN
DataTable dt;
private void button1_Click(object sender, EventArgs e)
{
try
{
openFileDialog1.ShowDialog();
string connectionString = string.Format("Provider = Microsoft.Jet.OLEDB.4.0;Data Source ={0};Extended Properties = Excel 8.0;", this.openFileDialog1.FileName);
var con = new OleDbConnection(connectionString);
var cmd = new OleDbCommand("select * from [sheet1$] where [MRN#]=#c", con);
cmd.Parameters.Add("#c", "33264");
con.Open();
var dr = cmd.ExecuteReader();
if (dr.HasRows)
{
dt = new DataTable();
dt.Load(dr);
}
dr.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
DataGridView dv = new DataGridView();
this.Controls.Add(dv);
dv.DataSource = dt;
}
}
EDIT:
As per your code you should try the below lines of code:
OleDbCommand _oleCmdSelect = new OleDbCommand(#"SELECT * FROM [" + excelSheets[0] + "]" + " Where [CustomerID#] = #custID" , objConn);
_oleCmdSelect.Parameters.Add("#custID", customerID);
OleDbDataAdapter oleAdapter = new OleDbDataAdapter();
oleAdapter.SelectCommand = _oleCmdSelect;
I have 1000 markers displayed on map which are retrieved from datagridview. Thats working fine but I want to display text as client name on these markers when clicked. is it possible to do that....
if (comboBox5.SelectedIndex == 4)//(REGION 1)
{
gMapControl1.MapProvider = GMap.NET.MapProviders.GoogleMapProvider.Instance; ;
GMap.NET.GMaps.Instance.Mode = GMap.NET.AccessMode.ServerOnly;
GMapOverlay markersOverlay = new GMapOverlay("VCS MAP");
gMapControl1.MaxZoom = 11;
gMapControl1.MinZoom = 1;
gMapControl1.Zoom = 1;
SqlDataReader myReader;
String Query = " SELECT top 200 Latitude,Longitude,client name FROM [ICPS].[dbo].[agreement latlongkir] where region ='5' ";
SqlConnection conDataBase = new SqlConnection(conString);
conDataBase.Open();
SqlCommand cmdDatabase = new SqlCommand(Query, conDataBase);
myReader = cmdDatabase.ExecuteReader();
gMapControl1.HoldInvalidation = true;
while (myReader.Read())
{
string Latitude = myReader["Latitude"].ToString();
string Longitude = myReader["Longitude"].ToString();
string ClientName = myReader["client name"].ToString();
gMapControl1.Position = new PointLatLng(float.Parse(Latitude), float.Parse(Longitude));
GMarkerGoogle marker = new GMarkerGoogle(gMapControl1.Position, GMarkerGoogleType.pink);
markersOverlay.Markers.Add(marker);
gMapControl1.Overlays.Add(markersOverlay);
marker.ToolTip = new GMapRoundedToolTip(marker);
marker.ToolTipText = myReader("ClientName");
}
}
Looks like your missing this. I have implemented something similar with no issue. I have some working code you can take a look at if this doesnt help.
marker.ToolTipMode = MarkerTooltipMode.Always;