10

I have a GridView control which shows a list of all employees. When user selects any employee from this list, the record is shown on a Web Form with all input controls pre-filled with the values.

I want to know any good approach to do this. Should I bind all input controls to any SqlDataSource or should I re-populate all input controls by picking values from the DataSet.

RKh
  • 13,818
  • 46
  • 152
  • 265
  • 1
    What about using a FormView in edit mode which is bound to a SqlDataSource. The SqlDataSource would be bound to the GridView's selectedvalue property. Selecting a user would automatically load them in the FormView. If this would be acceptable I'll write it up. – Peter Jul 17 '12 at 22:22

3 Answers3

7

First you add the select button on your GridView as:

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

then you add the OnRowCommand="RowCommand" property on GridView to call this function when the button is clicked and on code behind the function:

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);
            }    
        }
    }
}

I prefer this way of command button because you can add more commands than the select, or edit, even the delete or copy... the just index change can be done for any reason (eg by changing page) and is also need again the select.

I use the subsonic 2 DAL for loading the data from the database. A sample code from my programs is:

    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);
        }
   }
Aristos
  • 66,005
  • 16
  • 114
  • 150
2

I used this code in my application-

A better approach would call to this mothod on gridview_select_index_change() event

 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; 
    } 
}

EDIT

There might be better approach to do so but this works certainly fine.

akhil
  • 1,202
  • 3
  • 21
  • 43
  • I am also using this way but now I want to put this code in a separate class. The problem is how to pass the name of the control to this class. – RKh Jul 06 '12 at 09:01
  • 1
    why pass the control names. Just pass the dataset variable to the method of that class you want to call – akhil Jul 06 '12 at 09:49
  • Are you assuming the controls are filled via DataSet? If yes, where is the DataSet located? In the Web Form? – RKh Jul 06 '12 at 10:32
  • Anyway, the code that you posted is my code itself, from one of my old posts. – RKh Jul 06 '12 at 10:35
2

The way I would perform this task since you want to create a data access layer is to create a class which has all the properties

Class:

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;
  }
}

Web Page:

//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;
bluelightning1
  • 279
  • 2
  • 6