C#启用按钮使用数据表循环 [英] C# enabling button using datatable for loop
问题描述
我正在开发授权项目,我想编写代码来在打开窗体时启用带for循环的授权按钮。
授权按钮来自sql数据库
row.Enabled = true;
给我这个错误;
datarow不包含Enabled的定义,并且没有扩展方法Enabled接受类型为DataRow的
第一个参数(缺少
指令引用或程序集引用?)
这是我的代码
public void yetkiver()
{
SqlDataAdapter adapter1903 = new SqlDataAdapter();
SqlCommand cmd1903 =新的SqlCommand(选择不同的按钮名称授权其中Isactive = 1和usercode ='user1',con);
DataTable dt1903 = new DataTable();
DataSet ds1903 = new DataSet();
adapter1903.SelectCommand = cmd1903;
adapter1903.Fill(ds1903);
dt1903 = ds1903.Tables [0];
foreach(DataColumn col in dt1903.Columns)
{
foreach(DataRow row in dt1903.Rows)
{
row.Enabled = true;
<当然,一个 DataRow
没有 Enabled
属性。你想用这个名字来启用按钮。所以你必须在表单上找到它。您可以使用 Controls.Find
和LINQ:
foreach(DataRow row在dt1903.Rows中)
{
string buttonName = row.Field< string>(buttonname);
Button btn = this.Controls.Find(buttonName,true).OfType< Button>()。SingleOrDefault();如果发现多个
,则抛出一个异常if(btn!= null)
btn.Enaled = true;
$ b 这是一个奇怪的方法,如果有人想要改变按钮的名称?我不会在数据库中存储名称,但它们的类型/含义。不要使用循环来查找它们。
I am working on authorization project and I want to write code to enable authorized buttons with for loop while opening form.
Authorizated buttons cames from sql database
row.Enabled = true;
gives me this error;
"datarow does not contain a definition for "Enabled" and no extension method 'Enabled' accepting a
first argument of type 'DataRow' could be found(are you missing a
directive reference or an assembly reference?)"
This is my code
public void yetkiver()
{
SqlDataAdapter adapter1903 = new SqlDataAdapter();
SqlCommand cmd1903 = new SqlCommand("select distinct buttonname from authorization where Isactive=1 and usercode='user1'", con);
DataTable dt1903 = new DataTable();
DataSet ds1903 = new DataSet();
adapter1903.SelectCommand = cmd1903;
adapter1903.Fill(ds1903);
dt1903 = ds1903.Tables[0];
foreach (DataColumn col in dt1903.Columns)
{
foreach (DataRow row in dt1903.Rows)
{
row.Enabled = true;
}
}
}
解决方案 Of course a DataRow
has no Enabled
property. You want to enable the button with this name. So you have to find it on the form. You can use Controls.Find
and LINQ:
foreach (DataRow row in dt1903.Rows)
{
string buttonName = row.Field<string>("buttonname");
Button btn = this.Controls.Find(buttonName, true).OfType<Button>().SingleOrDefault(); // throws an exception if multiple found
if(btn != null)
btn.Enaled = true;
}
This is a weird approach by the way, what if someone wants to change the button-names? I would not store the names in database but their type/meaning. Don't use a loop to find them.
这篇关于C#启用按钮使用数据表循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!