根据C#中的长度更改标签文本行

时间:2017-04-20 09:17:46

标签: c# winforms combobox label access

所以我正在WinForms开发一个应用程序,我将Access数据库中的数据填充到Combobox。填充后,我将使用Combobox中的项目在我的标签上显示数据。这就是我必须填充数据的内容:

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

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

2 个答案:

答案 0 :(得分:0)

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

基本上你可以尝试一些事情:

- 如果是winforms,您可以设置标签的autosize property = true。

你可以试试这样的东西:

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

告诉我它是否有效。

答案 1 :(得分:0)

您只需要为标签设置两个属性:id = 2AutoSizeMaximumSize告诉标签增长(水平和垂直),但AutoSize将其限制为特定MaximumSizeWidth。所以。做这样的事情:

Height