2017-08-03 33 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(); 
    } 
}