Bryan
Bryan

Reputation: 8697

Data not displaying out despite auto-selecting gridview row

I'm trying to let the gridview auto-select the first row of data upon page load. However, in the gridview, it shows that the first row is being highlighted

enter image description here

but no data is being displayed in my textbox. The data only appears when i click the select button in my gridview again.

This is how i added the auto-select gridview row in my page load

protected void Page_Load(object sender, EventArgs e)
    {          
        if (!IsPostBack)
            {
                 gvnric.SelectedIndex = 0;
            }
        }

This is how i get my data from my gridview to my textbox

protected void gvnric_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session["nric"] = gvnric.SelectedRow.Cells[1].Text;


        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        con.Open();
        SqlCommand cm = new SqlCommand("Select fullname, contact, address, email From MemberAccount Where nric = '" + Session["nric"] + "'", con);
        SqlDataReader dr;
        dr = cm.ExecuteReader();
        if (dr.Read())
        {
            txtFullName.Text = dr["fullname"].ToString();
            txtAddress.Text = dr["contact"].ToString();
            txtContact.Text = dr["address"].ToString();
            txtEmail.Text = dr["email"].ToString();
        }
        con.Close();

        Image1.Attributes["src"] = "MemberNricCard.aspx?";
        Image1.Attributes["height"] = "200";
        Image1.Attributes["width"] = "200";
    }

But what could possibly caused the data not to be displayed when the first row already being selected upon page load.

Upvotes: 0

Views: 793

Answers (2)

Bryan
Bryan

Reputation: 8697

You can just call your gridview code in the page load

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            {

                gvnric.SelectedIndex = 0;
                gvnric_SelectedIndexChanged(this, EventArgs.Empty);
            }
        }

Upvotes: 0

Damith
Damith

Reputation: 63095

I would Re Factor the code as below :

PageLoad

if (!IsPostBack)
{
     gvnric.SelectedIndex = 0;
     LoadFormFields();
}

gvnric_SelectedIndexChanged

protected void gvnric_SelectedIndexChanged(object sender, EventArgs e)
{
    LoadFormFields();
}

and create LoadFormFields with what you have in gvnric_SelectedIndexChanged

Upvotes: 0

Related Questions