Подтвердить что ты не робот

Каков рекомендуемый способ заполнения всех элементов управления в веб-форме, когда пользователь выбирает запись?

У меня есть элемент управления GridView, который показывает список всех сотрудников. Когда пользователь выбирает любого сотрудника из этого списка, запись отображается в веб-форме со всеми элементами ввода, предварительно заполненными значениями.

Я хочу знать хороший подход к этому. Должен ли я привязывать все элементы управления вводами к любому SqlDataSource или мне нужно повторно заполнить все элементы управления вводом, выбирая значения из DataSet.

4b9b3361

Ответ 1

Сначала вы добавляете кнопку выбора в свой GridView как:

<asp:ButtonField Text="Select" CommandName="ViewMe" ButtonType="Button" />

то вы добавляете свойство OnRowCommand="RowCommand" на GridView для вызова этой функции при нажатии кнопки и в коде за функцией:

protected void RowCommand(object sender, GridViewCommandEventArgs e)
{
    // if the ViewMe command is fired
    if (e.CommandName == "ViewMe")
    {
        // go to find the index on the grid view
        int iTheIndexNow;
        if (int.TryParse(e.CommandArgument.ToString(), out iTheIndexNow))
        {
            // Set and highlight the selected
            TheGridView.SelectedIndex = iTheIndexNow;

            // do we have the table data id ?
            if (TheGridView.SelectedValue != null)
            {
                // now load the controls data using this id
                LoadValuesFromDatabaseToControls(TheGridView.SelectedValue);
            }    
        }
    }
}

Я предпочитаю этот способ командной кнопки, потому что вы можете добавлять больше команд, чем выбирать или редактировать, даже удалять или копировать... просто изменение индекса может быть сделано по любой причине (например, путем изменения страницы), а также нужно снова выбрать.

Я использую дозвуковой 2 DAL для загрузки данных из базы данных. Пример кода из моих программ:

    void LoadValuesFromDatabaseToControls(string editID)
    {
        // Load it from database
        AthUserMaiListName OneRow = new AthUserMaiListName(editID);

        if (OneRow.IsNotExist)
        {
            // a custom control that show messages on top.
            uResult.addMsg("Fail to load id " + editID, MsgType.error);
            // close the view of the controls
            dbViewPanel.Visible = false;
        }
        else // else we have the data and go for show them
        {
          // show this panel that contains the controls.
          dbViewPanel.Visible = true;

          // I keep my current edit id
          lblID.Text = editID;

          // just be sure that the select exist on DrowDownList
          MyUtils.SelectDropDownList(ddlEventType, OneRow.CAddedFrom);

          txtEmail.Text = OneRow.CEmail;
          txtFirstName.Text = OneRow.CFirstName;
          txtLastName.Text = OneRow.CLastName;
          txtInsideTitle.Text = OneRow.CInsideTitle;
          txtCompanyName.Text = OneRow.CCompanyName;        

          txtCreated.Text = DateTimeRender(OneRow.CreatedOn);
          txtModified.Text = DateTimeRender(OneRow.ModifiedOn);
        }
   }

Ответ 2

Я использовал этот код в своем приложении

Лучший подход вызвал бы этот mothod на событии gridview_select_index_change()

 private void PickValues(int SerialNum) 
{ 
    DataSet ds = new DataSet(); 
    try 
    { 
        string Query = "SELECT * FROM tw_main WHERE sno = " + SerialNum; 
        ds = reuse.ReturnDataSet(Query, "Scheme"); 

        //Add Scheme Code to new Session Variable 
        Session.Add("SerialNumber", ds.Tables[0].Rows[0]["sno"].ToString()); 
        //Set Update Flag 
        TaskFlag = "UPDATE"; 

        //Fill values of selected record on the Entry Form 
        if (ds.Tables[0].Rows[0]["schm_code"].ToString().Length > 0) 
            lblSchemeCode.Text = ds.Tables[0].Rows[0]["schm_code"].ToString(); 

        ddlType.SelectedValue = ds.Tables[0].Rows[0]["schemetype"].ToString(); ddlDistrict.Text = ds.Tables[0].Rows[0]["dist_nm"].ToString(); ddlBlock.Text = ds.Tables[0].Rows[0]["block_nm"].ToString(); 
        txtSchemeName.Text = ds.Tables[0].Rows[0]["schm_nm"].ToString(); 
        txtPopulation2001.Text = ds.Tables[0].Rows[0]["population_2001"].ToString(); 
        txtSupplySource.Text = ds.Tables[0].Rows[0]["supply_source"].ToString(); 
        txtApprovalYear.Text = ds.Tables[0].Rows[0]["yr_approval"].ToString(); 
        txtApprovalLetterNum.Text = ds.Tables[0].Rows[0]["approval_letter_num"].ToString(); 
        txtApprovalAmount.Text = ds.Tables[0].Rows[0]["sch_apr_amt"].ToString(); 
        txtWaitedLetterNum.Text = ds.Tables[0].Rows[0]["sch_waited_details"].ToString(); 
        txtSchTransferLetterNum.Text = ds.Tables[0].Rows[0]["schm_trans_details"].ToString(); 
        txtSchTransferDate.Text = ds.Tables[0].Rows[0]["schm_trans_date"].ToString(); 
        txtOtherRemarks.Text = ds.Tables[0].Rows[0]["remarks"].ToString(); 
    } 
    catch (Exception ex) 
    { 
        ScriptManager.RegisterClientScriptBlock(this.Page, this.Page.GetType(), "Warning", "alert('" + ex.Message.ToString() + "');",true); 
    } 
    finally 
    { 
        ds.Dispose(); 
        gridSerialNo = 0; 
    } 
}

ИЗМЕНИТЬ

Там может быть лучший подход, но это работает отлично.

Ответ 3

Способ выполнения этой задачи, так как вы хотите создать уровень доступа к данным, - это создать класс, который имеет все свойства

Класс:

public class tw_main
{
     public string SchemeCode {get;set;}
}

DAL:

public class dal
{
  public tw_main getSelectedValue(pass the parameters required by the method)
  {
    //your connection and query code
    var twmain = new tw_main();
    twmain.SchemaCode =  ds.Tables[0].Rows[0]["schm_code"].ToString(); 

    return twmain;
  }
}

Веб-страница:

//depending upon where you add this a reference may need to be imported (using) to the namespace
  var dalObj = new dal();
  var tw = dalObj.getSelectedValue();
lblSchemeCode.Text = tw.SchemaCode;