2017-04-20 64 views
0

因此,我正在开发一个应用程序WinForms,并将数据从Access数据库填充到Combobox。填充后,我将使用Combobox中的项目在我的标签上显示数据。这是我有数据填充:根据C中的长度更改标签文本行#

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()); 
    } 
} 
Combobox选择的指数的事件里面

然后,我将使用这个代码:

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

基本上技术标签太大,当它到达的长度变化线。这是可行的吗?

+0

您是否尝试设置标签的AutoSize属性? – Digvijay

+0

将它设置为false并根据我想要的尺寸来确定它的大小? – Rekcs

+0

啊..那么你可以使用System.Drawing.Graphics命名空间中的MeasureString来达到这个目的。您可以得到该字符串在屏幕上的宽度,并相应地设置标签宽度。 – Digvijay

回答

0

你的问题不是很清楚。你正在使用WPF或Winforms?

Basicly你可以尝试喜欢的几件事情:

- 如果的WinForms,您可以设置自动调整大小属性=您的标签也是如此。

,你可以尝试这样的事情:

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




    } 

或者,如果你可以给一个固定宽度的标签,您可以检查字符串的长度增加一个新行:

 int lngth = 100; 
    if(sTech.Length > lngth) 
    { 
     sTech = sTech.SubString(0, lngth) + Environment.NewLine + sTech.SubString(lngth); 
    lblTech.Text = sTech; 
    } 

告诉我,如果它的工作。

+0

我用它更新了这个问题。那么我将使用该方法 – Rekcs

0

您只需要为您的标签设置两个属性:AutoSizeMaximumSizeAutoSize指示标签生长(水平和垂直),但MaximumSize将其限制为某些WidthHeight。所以。只是做这样的事情:

label1.AutoSize = true; 
label1.MaximumSize = new Size(100, 600); 
label1.Text = "test string which is pretty long";