2017-01-15 13 views
1

私のOleDbデータベースで特定のユーザーを検索する検索機能があります。ユーザーごとに、テーブル内の行が作成されます。テーブルの行には、自分の名前、管理者かどうかを示すブール値、削除ボタンが含まれます。削除ボタンは期待通りに機能していません。リンクされているメソッドは実行されません。私のコードはSearch_Clickイベントにあり、管理者が検索ボタンをクリックして特定のユーザーを検索した直後に実行されます。 私のコードから、代わりにPage_Loadにあらかじめ定義されたボタンを配置しようとしましたが、期待通りに機能します。 Search_Clickからボタンを操作するにはどうしたらいいですか? 基本的には、ユーザーの検索テキストに従ってLinkBut​​tonを動的に作成し、検索ボタン(Search_Click)をクリックした後、クリックイベントをページロードイベントに登録する方法を見つける必要があります。リンクボタンには検索ボタンのクリックイベントで作成する必要がありますが、ページロードによって登録する必要があります。ASP.NET(C#)の動的ボタンに関する問題

using (OleDbDataReader reader = cmd.ExecuteReader()) 
{ 
    Table table = new Table(); 
    TableRow row = new TableRow(); 
    TableCell cell = new TableCell(); 
    Label label = new Label(); 
    while (reader.Read()) 
    { 
     row = new TableRow(); 
     cell = new TableCell(); 
     label = new Label(); 

     label.Text = reader.GetString(0); 
     cell.Controls.Add(label); 
     cell.BorderStyle = BorderStyle.Solid; 
     row.Cells.Add(cell); 

     cell = new TableCell(); 
     label = new Label(); 

     label.Text = reader.GetBoolean(1).ToString(); 
     cell.Controls.Add(label); 
     cell.BorderStyle = BorderStyle.Solid; 
     row.Cells.Add(cell); 

     cell = new TableCell(); 
     LinkButton button = new LinkButton(); 

     button.Text = "Delete"; 
     button.ID = (string) reader["uName"]; 
     button.CommandName = (string)reader["uName"]; 
     button.Click += new EventHandler(DeleteUser); 

     cell.Controls.Add(button); 
     cell.BorderStyle = BorderStyle.Solid; 
     row.Cells.Add(cell); 

     table.Rows.Add(row); 
    } 
    table.Style.Add(HtmlTextWriterStyle.MarginLeft, "auto"); 
    table.Style.Add(HtmlTextWriterStyle.MarginRight, "auto"); 
    TableHolder.Controls.Add(table); 
} 

は、deleteuser:

protected void DeleteUser(object sender, EventArgs e) 
    { 
     try 
     { 
      LinkButton button = (LinkButton)sender; 
      string path = Server.MapPath(@"App_Data/ArcadeDatabase.accdb"); 
      using (OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + "; Persist Security Info = False;")) 
      { 
       try 
       { 
        con.Open(); 
       } 
       catch(Exception ex) 
       { 
        helper.Log("OleDbError", ex.Message); 
       } 
       if(con.State == System.Data.ConnectionState.Open) 
       { 
        using (OleDbCommand cmd = new OleDbCommand("DELETE * FROM ArcadeDatabase WHERE uName ='" + button.CommandName + "';", con)) 
        { 
         try 
         { 
          cmd.ExecuteNonQuery(); 
         } 
         catch (Exception ex) 
         { 
          helper.Log("OleDbError", ex.Message); 
         } 
        } 
       } 
       con.Dispose(); 
      } 
      path = ""; 
     } 
     catch (Exception ex) 
     { 
      helper.Log("Admin", ex.Message); 
     } 
    } 
+0

を。少なくとも、DeleteUserイベントのコードを提供する必要があります。 – Sefe

+0

私は自分の質問を編集して、今はDeleteUserコードを含んでいます:)しかし、私が言ったように、私はブレークポイントを置いたし、実行もしません。 – Itay080

答えて

2

ダイナミックコントロールのイベントハンドラが(see this link)をトリガーするPage_Load/Page_Initイベント中に登録する必要があります。

したがって、削除ボタンとそのイベントハンドラをpage_loadまたはinitに追加する必要があります。 see this


UPDATE、Page_Initイベントでポストバックを引き起こすコントロールのIDを見つけるために:

OK、私はそれを問題なく行うことができる証拠にこのコードを追加します。

どのように動作するかを確認するには、新しいWeb Formを作成し、次のHTML &コードビハインドを貼り付けます。次に、アプリを実行してSearch TextBox(例:JohnまたはAli)に名前を入力し、Search Buttonを押して結果をフィルタリングします。

public partial class _Default : Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     string searchName = ""; 
     if (SearchTextBox.Text != "") //if (this.GetPostBackControlUniqueID() == Search.UniqueID) //Search button is clicked! 
     { 
      searchName = SearchTextBox.Text; 
     } 
     addTable(searchName); 
    } 

    void addTable(string searchName) 
    { 
     string[] data = new[] { 
      "John, false, usrJohn" 
      ,"Alex, false, usrAlex" 
      ,"Ali, true, usrAli" 
     }; 

     //using (OleDbDataReader reader = cmd.ExecuteReader()) 
     //{ 
      Table table = new Table(); table.CellPadding = 10; 
      TableRow row; 
      TableCell cell; 
      Label label; 

      foreach(string dataItem in data) //while (reader.Read()) 
      { 
       string[] reader = dataItem.Split(','); 
       if (reader[0].IndexOf(searchName, StringComparison.OrdinalIgnoreCase) < 0) continue; //search not found (in real app, you use sql where clause for this, but this is just for test) 

       row = new TableRow(); 
       cell = new TableCell(); 
       label = new Label(); 

       label.Text = reader[0].Trim(); //reader.GetString(0); 
       cell.Controls.Add(label); 
       cell.BorderStyle = BorderStyle.Solid; 
       row.Cells.Add(cell); 

       cell = new TableCell(); 
       label = new Label(); 

       label.Text = reader[1].Trim(); //reader.GetBoolean(1).ToString(); 
       cell.Controls.Add(label); 
       cell.BorderStyle = BorderStyle.Solid; 
       row.Cells.Add(cell); 

       cell = new TableCell(); 
       LinkButton button = new LinkButton(); 

       button.Text = "Delete"; 
       string uName = reader[2].Trim(); 
       button.ID = uName; //(string)reader["uName"]; 
       button.CommandName = uName; //(string)reader["uName"]; 
       button.Click += new EventHandler(DeleteUser); 

       cell.Controls.Add(button); 
       cell.BorderStyle = BorderStyle.Solid; 
       row.Cells.Add(cell); 

       table.Rows.Add(row); 
      } 

      table.Style.Add(HtmlTextWriterStyle.MarginLeft, "auto"); 
      table.Style.Add(HtmlTextWriterStyle.MarginRight, "auto"); 

      TableHolder.Controls.Add(table); 
     //} //end using OleDbDataReader reader 
    } 

    protected void Search_Click(object sender, EventArgs e) 
    { 
     //addTable(SearchTextBox.Text); //already done in Page_Load 
    } 

    protected void DeleteUser(object sender, EventArgs e) 
    { 

     LinkButton button = (LinkButton)sender; 
     //using (OleDbCommand cmd = new OleDbCommand("DELETE * FROM ArcadeDatabase WHERE uName ='" + button.CommandName + "';", con)) 
     string sql = "DELETE * FROM ArcadeDatabase WHERE uName ='" + button.CommandName + "';"; 
     //execute the sql ... (in real app) 

     TableHolder.Controls.Add(new LiteralControl("The sql was: " + sql)); 
    } 

    protected void Button1_Click(object sender, EventArgs e) 
    { 
     Label1.Text = DateTime.Now.ToString("HH:mm:ss"); 
    } 


} //end class 

そして、これがUniqueIDPostBackのコントロールを取得するためのヘルパー拡張メソッドです:このコードでは何も問題はないように思わ

// *********************************************************************** 
public static class MyWebPageExtensions 
{ 

    public static string GetPostBackControlUniqueID(this Page page) 
    { 
     if (!page.IsPostBack) 
      return string.Empty; 

     Control control = null; 

     string controlName = page.Request.Params["__EVENTTARGET"]; //this method works only for link buttons which use javascript: __doPostBack(...) and not input type=submit buttons. Note: it is also available in Request.Form collection but this doesn't require to loop over Form. 
     if (!String.IsNullOrEmpty(controlName)) 
     { 
      control = page.FindControl(controlName); 
     } 
     else 
     { 
      // __EVENTTARGET is null, the control is a button (not javascript linkButton), we need to iterate over the form collection to find it 
      foreach (string id in page.Request.Form) 
      { 
       // handle ImageButton they having an additional "quasi-property" in their Id which identifies mouse x and y coordinates 
       if (id.EndsWith(".x") || id.EndsWith(".y")) 
       { 
        string id2 = id.Substring(0, id.Length - 2); 
        control = page.FindControl(id2); 
       } 
       else 
       { 
        control = page.FindControl(id); 
       } 

       if (control is IButtonControl) break; 

      } 
     } 

     return control == null ? String.Empty : control.UniqueID; 
    } 

} 
+0

ありがとうございますが、私はここからどのように進めていくべきかは分かりません。私は通常モードのモードを持っています。つまり、ユーザーはデータベース内で何も検索していません。また、ユーザーがデータベース内の誰かを検索しているというモードがあります。現在トリガーされていますか?どのくらいのエントリが現れたかをどのように知るのですか?テーブルのユーザーの名前とページの読み込み時にそのボタンを追加する正確な場所を確認するにはどうすればよいですか? – Itay080

+0

この 'button.CommandName =(string)reader [" uName "];の助けを借りてあなたのコードには既に見たように、あなたはどのユーザを削除するのか知っています。 –

+0

ああ、私はページロードでイベントを登録する必要があるので、今すぐ取得します。しかし、どのくらい多くのボタンを登録する必要があるのか​​分かりますか?どのようにループすることができますか?私はあなたに方向性のためだけにコードを書くように求めていません。 – Itay080

関連する問題