Thursday, June 11, 2009

ASP.NET C#

1. Read data from DataReader
Syntax: 1

DBAccess db = new DBAccess();
IDataReader dr;
dr = db.ExecuteReader("select * from tblQuestionAnswer where QId='" + Request.QueryString["QuestionId"].ToString() + "'");
if (dr.Read())
{
this.txtQuestionNumber.Text = dr["QuestionNumber"].ToString();
this.txtQuestionName.Text= (string)dr["QuestionName"];
this.txtAnswerName.Text =(string)dr["AnswerName"];
this.txtAnswerNumber.Text=dr["AnswerNumber"].ToString();
this.chkIsActive.Checked =(bool)dr["IsActivate"];
//this.chkIsActive.Checked = dr.GetBoolean(dr.GetOrdinal("IsActivate"));
}
dr.Close();

Syntax: 2
DBAccess db = new DBAccess();
IDataReader dr;
dr = db.ExecuteReader("select * from tblAnswer where AnswerId='" + Request.QueryString["AnswerId"].ToString() + "'");
if (dr.Read()){
string str = dr.GetInt32(dr.GetOrdinal("QuestionId")).ToStrin();
this.ddlQuestion.ClearSelection();
this.ddlQuestion.Items.FindByValue(str).Selected = true;
this.txtAnswerKh.Text = dr.GetString(dr.GetOrdinal("AnswerNameKh"));
if (dr.GetString(dr.GetOrdinal("AnswerNameEng"))==null){
this.txtAnswerEng.Text = string.Empty;
}else{
this.txtAnswerEng.Text = dr.GetString(dr.GetOrdinal("AnswerNameEng"));
} this.chkCorrectAnswer.Checked = dr.GetBoolean(dr.GetOrdinal"CorrectAnswer"));
this.chkIsActive.Checked = dr.GetBoolean(dr.GetOrdinal("IsActivate"));
}
dr.Close();

2. Select value from dropdownlist by criteria
if (dr.Read()){
string str = dr.GetInt32(dr.GetOrdinal("QuestionId")).ToStrin();
this.ddlQuestion.ClearSelection();
---
}
dr.Close();

3. How to bind data to dropdownlist
DBAccess db = new DBAccess();
DataSet ds = new DataSet();
ds = db.ExecuteDataSet("SELECT QuestionId, QuestionNameEng, QuestionNameKh, CASE WHEN QuestionNameEng IS NULL THEN QuestionNameKh WHEN QuestionNameEng IS NULL THEN QuestionNameEng ELSE QuestionNameEng + space(3) + QuestionNameKh END AS Display FROM dbo.tblQuestion order by QuestionId");
this.ddlQuestion.DataSource = ds.Tables[0];
this.ddlQuestion.DataTextField = "Display";
this.ddlQuestion.DataValueField = "QuestionId";
this.DataBind();

Code behind:
protected void gv_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Delete")
{
string strSID = e.CommandArgument.ToString();
string strSQL = "DELETE FROM [dbo].[tblAnswer] WHERE AnswerId=" + strSID;
DBAccess dbDelete = new DBAccess();
dbDelete.ExecuteNonQuery(strSQL);
Response.Redirect("Answer.aspx?Accessmode=delete");
}
}
protected void gv_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gv.PageIndex = e.NewPageIndex;
bindGridView();
}

No comments: