Thursday, February 3, 2011

Get Primary key value in gridview on edit command


Step 1: Create a form and put div that contain questionid and question description style="Display:none", to get question id.


Step 2: Put the following code on rowcommand of gridview

protected void GridView1_RowCommand1(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("edits"))
            {
                int index = Convert.ToInt32(e.CommandArgument.ToString());
                int ServerID = Convert.ToInt32(GridView1.DataKeys[index].Value);
                TxtQuestionId.Text = ServerID.ToString();

                SqlConnection mycon = new SqlConnection(connectionstring);
                SqlCommand mycmd = new SqlCommand("select * from QuestionMaster where                                                             QuestionId='"+TxtQuestionId.Text+"'", mycon);
                mycon.Open();
                SqlDataAdapter myadpt = new SqlDataAdapter(mycmd);
                DataSet ds = new DataSet();
                myadpt.Fill(ds);
                ddCourse.SelectedValue = ds.Tables[0].Rows[0]["CourseId"].ToString();
                ddTopic.SelectedValue = ds.Tables[0].Rows[0]["TopicId"].ToString();
                TxtQuestion.Text = ds.Tables[0].Rows[0]["Question"].ToString();
      }
//To hide particular cell from Grid View 
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            e.Row.Cells[1].Visible = false;
        }



Step 3: And at last put the following code on submit button click

 protected void Button1_Click(object sender, EventArgs e)
        {
            SqlConnection mycon = new SqlConnection(connectionstring);
            SqlCommand mycmd = new SqlCommand("UpdateQuestionMaster", mycon);
            mycmd.CommandType = CommandType.StoredProcedure;
            mycmd.Parameters.Add("@CourseId", SqlDbType.Int).Value = ddCourse.SelectedValue;
            mycmd.Parameters.Add("@TopicId", SqlDbType.Int).Value = ddTopic.SelectedValue;
            mycmd.Parameters.Add("@Questiondescription", SqlDbType.NVarChar).Value = TxtQuestionDes.Text;
            mycmd.Parameters.Add("@Question", SqlDbType.NVarChar).Value = TxtQuestion.Text;
            mycmd.Parameters.Add("@QuestionId", SqlDbType.Int).Value = TxtQuestionId.Text;
            mycon.Open();
            mycmd.ExecuteNonQuery();
        }


Also see my other blogs: Reset Table id to zero in sql server
                                                               Tree View using database

No comments:

Post a Comment