2017-08-03 32 views
2

我创建了Windows窗体应用程序,并且使用label_1.Visible = false;使我的标签不可见。C#如何制作标签的可见首字母

我只想使标签的第一个字母可见。

我该怎么办呢?

+1

''label_1.Text = label_1.Text [0];''好足够? –

+0

你想做一些markee的?逐字显示等等? – Gusman

+0

@Guman,是的,我想要这个 – NoobGuy123

回答

4

可见性是全有或全无的概念:如果一个标签或任何其他组件都被标记为不可见,则它们都不会出现在表单上。

如果要仅在标签中显示string的前几个字母,请使用Substring方法指定标签的文本。为了使这项工作,实际文本必须存储在某个地方的标签之外 - 比如,在labelText领域:

private string labelText = "Quick brown fox"; 
... 
label_1.Text = labelText.Substring(0, 1); // Only the first character is shown 
+0

这是对我来说最好的方法,谢谢 – NoobGuy123

0

字符串在技术上是字节数组,意味着每个字母都可以用索引访问。

例如:

string x = "cat"; 
char y = x[0]; 
// y now has a value of 'c'! 

弦上执行此被用于您的标签和使用您的标签结果来代替。我还想补充说,你需要设置label_1.Visible = true;,否则什么都不会出现。

运用上面的代码,您应该到达的东西是这样的:

label_1.Visible = true; 
label_1.text = label_1.text[0].ToString(); 

希望对你有用!

1

根据您回答一个评论,这听起来像你有兴趣在一个帐篷式显示。这里有一种方法可以做到这一点,将整个字符串存储在一个变量中,然后只在标签中显示其中的一部分。

在下面的例子中,我们有一串文本显示存储在一个变量中。我们添加一个标签来显示文本,并使用计时器重复更改文本,使其看起来像滚动。

要看到它的行动,开始一个新的Windows窗体应用程序项目,并与下面的代码替换部分窗体类:

public partial class Form1 : Form 
{ 
    // Some text to display in a scrolling label 
    private const string MarqueeText = 
     "Hello, this is a long string of text that I will show only a few characters at a time. "; 

    private const int NumCharsToDisplay = 10; // The number of characters to display 
    private int marqueeStart;     // The start position of our text 
    private Label lblMarquee;     // The label that will show the text 

    private void Form1_Load(object sender, EventArgs e) 
    { 
     // Add a label for displaying the marquee 
     lblMarquee = new Label 
     { 
      Width = 12 * NumCharsToDisplay, 
      Font = new Font(FontFamily.GenericMonospace, 12), 
      Location = new Point {X = 0, Y = 0}, 
      Visible = true 
     }; 
     Controls.Add(lblMarquee); 

     // Add a timer to control our marquee and start it 
     var timer = new System.Windows.Forms.Timer {Interval = 100}; 
     timer.Tick += Timer_Tick; 
     timer.Start();    
    } 

    private void Timer_Tick(object sender, EventArgs e) 
    { 
     // Figure out the length of text to display. 
     // If we're near the end of the string, then we display the last few characters 
     // And the balance of characters are taken from the beginning of the string. 
     var startLength = Math.Min(NumCharsToDisplay, MarqueeText.Length - marqueeStart); 
     var endLength = NumCharsToDisplay - startLength; 

     lblMarquee.Text = MarqueeText.Substring(marqueeStart, startLength); 
     if (endLength > 0) lblMarquee.Text += MarqueeText.Substring(0, endLength); 

     // Increment our start position 
     marqueeStart++; 

     // If we're at the end of the string, start back at the beginning 
     if (marqueeStart > MarqueeText.Length) marqueeStart = 0;    
    } 

    public Form1() 
    { 
     InitializeComponent(); 
    } 
}