2015-06-25 35 views
0

我希望有人可以幫助這個。我一直在試圖爲WinForm創建一個新的基類。我想要做的是讓這個基類遍歷它所具有的所有表適配器,並更新它們的連接字符串,而不需要任何人向表單添加任何代碼。他們只是將表適配器放在表單上,​​不用擔心連接字符串設置,因爲它全部在基類中處理。C#反射。 Set TableAdapter ConnectionString

我遇到的問題是我的反射代碼可以找到屬性,但無法設置它。有人可以幫忙嗎?

下面是代碼(更新)

public class cFormWS : Form 
{ 
    public string ConnectionStringToUse { get; set; } 

    public cFormWS() 
    { 
     Load += cFormWS_Load; 
    } 

    void cFormWS_Load(object sender, EventArgs e) 
    { 
     InitiliseTableAdapters(); 
    } 

    private void InitiliseTableAdapters() 
    {   
     var ListOfComponents = EnumerateComponents(); 

     foreach (var ItemComp in ListOfComponents) 
     { 
      if (ItemComp.ToString().ToLower().EndsWith("tableadapter")) 
      { 
       var ItemCompProps = ItemComp.GetType().GetRuntimeProperties(); 

       var TASQLConnection = ItemCompProps.FirstOrDefault(w => w.PropertyType == typeof(System.Data.SqlClient.SqlConnection)); 

       if (TASQLConnection != null) 
       { 
        var property = typeof(System.Data.SqlClient.SqlConnection).GetProperty("ConnectionString"); 

        // How do I set the value ? 

        string value = "some new connection string"; 

        var ConvertedProperty = Convert.ChangeType(value, property.PropertyType); 

        // tried seting value. not working "object does not match target type" 
        property.SetValue(TASQLConnection, ConvertedProperty, null); 


        //// tried using a method. not working "object does not match target type" 
        //var m = property.SetMethod; 
        //ParameterInfo[] parameters = m.GetParameters(); 
        //m.Invoke(m, parameters); // m.Invoke(this, parameters); // m.Invoke(ItemComp, parameters); 
       }      
      }     
     } 
    } 

    private IEnumerable<Component> EnumerateComponents() 
    { 
     return from field in GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) 
       where typeof(Component).IsAssignableFrom(field.FieldType) 
       let component = (Component)field.GetValue(this) 
       where component != null 
       select component; 
    } 
+0

你不需要反射這裏(或者你的代碼不會使其預期用途的任何意義)。 – leppie

+0

據我所知,沒有其他辦法可以自動完成我想要的任務。 –

+0

只有在TableAdapter不共享公共基類時纔會出現這種情況。可以? MSDN對此很模糊。 – leppie

回答

1

編輯:

當你做SetValue,你需要在你想設置的屬性的對象通過。

  • 在你的第一個示例代碼,您在ItemComp通過:這是不正確的,因爲在ConnectionString是這是ItemComp
  • 屬性在你編輯的問題(和我原來的答覆)你SqlConnection的屬性通過TASqlConnection。然而,這是不是基於對象
  • 正確的方法是從ItemComp對象獲得的價值,並把它傳遞的對象,但PropertyInfo

property.SetValue(TASQLConnection.GetValue(ItemComp), ConvertedProperty, null);

ORIGINAL(不正確)解答:

您正試圖設置ConnectionString屬性ItemComp。 ConnectionString不是TableAdapter的屬性,而是SqlConnection(屬於TableAdapter的屬性)的屬性。

設置屬性應該是這樣的正確方法:

property.SetValue(TASQLConnection, ConvertedProperty, null); 
+0

不是。相同的錯誤消息。我已經嘗試了很多不同的組合。 –

+0

是的,問題在於你正在傳遞'PropertyInfo'對象,而不是實際的對象。請參閱我編輯的答案以獲取解釋和修復 – Kenneth

+0

感謝您的回答。它仍然沒有工作。我現在有一個不同的錯誤。 調用的目標引發了異常。 –