I have this table in a gridview.
ID Question_No Question Survey_ID
-----------------------------------------------------------
1 1 Whats you name? 44
2 2 How Old Are you? 44
3 3 Whats your favorite hobby 44
4 4 What did you study? 44
I want to add a remove button to the page that works like this: When i delete one of these records, i want to update the question_no of all the questions automatically as long as the survey_ID is 44. For example, If i delete the 2nd question, it would become like this.
ID Question_No Question Survey_ID
-----------------------------------------------------------
1 1 Whats you name? 44
3 2 Whats your favorite hobby 44
4 3 What did you study? 44
How do i do this? i figured it must be a loop, but i have no idea how to even approach it.
EDIT: This is my remove button code
protected void RemoveQuestionButton_Click(object sender, EventArgs e)
{
try
{
DataRowView r;
r = ((DataRowView)QuestionsGridView.GetRow(QuestionsGridView.FocusedRowIndex));
Session["Question_ID"] = r[0];
if (Session["Question_ID"] != null)
{
SqlConnection connection = DatabaseConnection.GetSurveySystemConnection();
string delStatement1 = "DELETE FROM Questions WHERE ID =" + Session["Question_ID"];
string delStatement2 = "DELETE FROM Question_Options where Question_ID=" + Session["Question_ID"];
SqlCommand cmd = new SqlCommand(delStatement1, connection);
SqlCommand cmd2 = new SqlCommand(delStatement2, connection);
cmd.CommandType = CommandType.Text;
cmd2.CommandType = CommandType.Text;
try
{
cmd2.ExecuteNonQuery();
cmd.ExecuteNonQuery();
ConfirmLbl.ForeColor = System.Drawing.ColorTranslator.FromHtml("Green");
ConfirmLbl.Text = "Question & Options Deleted Successfully!";
QuestionsGridView.DataBind();
}
catch (Exception)
{
ConfirmLbl.ForeColor = System.Drawing.ColorTranslator.FromHtml("red");
ConfirmLbl.Text = "This Question Has Options Linked to it...";
}
finally
{
connection.Close();
}
}
}
catch (Exception)
{
ConfirmLbl.ForeColor = System.Drawing.ColorTranslator.FromHtml("red");
ConfirmLbl.Text = "You need to select a Question to edit...";
}
}
This can be done with a single update statement.
Here is an SQLFiddle example: http://sqlfiddle.com/#!6/0a1e7/1