简体   繁体   中英

Calling Item_command Event from page_load function

Scenario:I have two divs on a page div1 contains datalist (datalist1) and div2 contains controls that are populated on item-command event of data-list.

Problem : I want to call item_command event for 1st element of datalist1 on page_Load. how can I do that and what parameters shall i pass to item_command event?

item_command event:

protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)
{

      DataList1.SelectedIndex = e.Item.ItemIndex;

                if (e.CommandName.Equals("MID"))
                {
         AnswerId = Convert.ToInt32(DataList1.DataKeys[e.Item.ItemIndex].ToString());// a global variable

                    DataClasses1DataContext db = new DataClasses1DataContext();
                    var memos = (from m in db.Memos
                                 where m.memoId == AnswerId
                                 select m).First();


                       legendtitle.InnerText = memos.title.ToString();


                    TextBox2.Text = memos.description.ToString();        
}

If your event handler contains code that you want to run independently of the event firing, refactor the method to remove that code to a separate method. (Probably everything after setting AnswerId.) Then you can call that separate method without faking event args.

try like this :

call this method on page_load as

BindingMethod(0);            //for 1st selection

and in DataList1_ItemCommand as

BindingMethod(e.Item.ItemIndex); 

and declare method as below

public void BindingMethod(int index)

{
 DataList1.SelectedIndex = index;

            if (e.CommandName.Equals("MID"))
            {
     AnswerId = Convert.ToInt32(DataList1.DataKeys[index].ToString());// a global variable

                DataClasses1DataContext db = new DataClasses1DataContext();
                var memos = (from m in db.Memos
                             where m.memoId == AnswerId
                             select m).First();


                   legendtitle.InnerText = memos.title.ToString();


                TextBox2.Text = memos.description.ToString(); 


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM