如何在c#winForm中使用Location定义声明字符串变量? [英] How to declare string variable with Location definition in c# winForm?

查看:241
本文介绍了如何在c#winForm中使用Location定义声明字符串变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  string  labelName =   lblCity; 





lblAmtInWords 是标签名称我在标签属性中给出了..



 lblAmtInWords.Location =  new  Point(lblAmtInWords.Location.X, 238 ); 
lblAmtInWords.Location = new Point(lblAmtInWords.Location.Y, 684 );



i希望传递 lblCity 而不是 lblAmtInWords



 lblCity.Location =  new  Point(Convert.ToInt32(split1 [i +  1 ]),Convert.ToInt32(split1 [i +  2 ])); 





得到这样的错误...



错误:'string'不包含'Location'的定义,也没有扩展方法'Location'接受类型'string'的第一个参数(你是否缺少using指令或汇编引用?)

解决方案

我会使用字典< String,Label> 来达到目的,例如

字典<字符串,标签> labelByName =  new  Dictionary< string,Label>(); 
labelByName.Add( price,lblPrice);
labelByName [ price]。text = 请指定价格;


如果你想传递一个label,然后传递一个标签:一个字符串没有Location属性,因为它不是一个可显示的项目 - 只有基于控件的类。



你可以传递一个标签到一种非常容易的方法:

  public   void  MyMethod(Label lab, string  str,Point p)
{
lab.Location = p;
lab.Text = str;
}
...
MyMethod(myLabelToTamperWith, 一些文字 new 点( 100 100 ));

但是如果你试图传递一个引用标签的变量的名称,那么它会变得更复杂,你必须根据你的环境使用Reflection或类似的东西。通常,这是一个标志,你已经做了比它需要的复杂得多的事情! :笑:


string labelName = "lblCity";



lblAmtInWords is label name which i given in label properties..

lblAmtInWords.Location = new Point(lblAmtInWords.Location.X, 238);
lblAmtInWords.Location = new Point(lblAmtInWords.Location.Y, 684);


i want to pass the lblCity instead of lblAmtInWords

lblCity.Location = new Point(Convert.ToInt32(split1[i + 1]), Convert.ToInt32(split1[i + 2]));



getting error like this...

error:'string' does not contain a definition for 'Location' and no extension method 'Location' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?)

解决方案

I would use a Dictionary<String, Label> for the purpose, e.g.

Dictionary<String, Label> labelByName = new Dictionary<string, Label>();
labelByName.Add("price", lblPrice);
labelByName["price"].Text = "Please specify the price";


If you want to pass a label, then pass a label: a string does not have a Location property because it's not a displayable item - only Control based classes are.

You can pass a label to a method very easily:

public void MyMethod(Label lab, string str, Point p)
   {
   lab.Location = p;
   lab.Text = str;
   }
...
   MyMethod(myLabelToTamperWith, "Some text", new Point(100,100));

But if you are trying to pass the name of a variable which refers to a label then it gets much more complex, and you have to faff about with Reflection or similar depending on your environment. Normally, it's a sign you have made something far more complicated than it needs to be! :laugh:


这篇关于如何在c#winForm中使用Location定义声明字符串变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆