Merhaba arkadaslar, GridView kullanimini kisaca inceleyecegiz. GridView’e veriyi cekmeden once “AutoGenerateColumns=”False”” olarak ayarliyoruz ve gosterilmesini istedigimiz sutunlari el ile ekliyoruz. (Resim 1, Resim 2)
Resim 2’de ekledigimiz “BoundField” nesnelerinin “DataField” degerlerine veritabanindaki tablomuzdan gosterilmesini istediginiz sutun adlarini giriyoruz. Degistirilmesini istemediginiz nesnelerin (Id gibi) “ReadOnly” ozelligini “True” yapmayi unutmayin.
Simdi veritabanindan verilerimizi cekiyoruz. Baglanti cumlelerini yazmiyorum.
public void GetAllTest()
{
ConnectionControl();
SqlDataAdapter Da = new SqlDataAdapter("SELECT * FROM AllTests",myConnection);
DataSet Ds = new DataSet();
Da.Fill(Ds);
GridView1.DataSource=Ds;
GridView1.DataBind();
}
GridView’e veriyi cektik. GridView’de kullanacagimiz olaylar;
- onrowcancelingedit
- onrowdeleting
- onrowediting
- onrowupdating
- onselectedindexchanging
Olaylar su sekilde kodlanacak;
//Edit Cancel
protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
GridView1.EditIndex = -1;
GetAllTest();
}
//Delete
protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
ConnectionControl();
SqlCommand Cmd = new SqlCommand("DELETE FROM Users WHERE userID=@userId", myConnection);
Cmd.Parameters.Add("@userId",SqlDbType.Int).Value = Convert.ToInt32(GridView1.Rows[e.RowIndex].Cells[3].Text);
Cmd.ExecuteNonQuery();
GetAllTest();
}
//Edit
protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
GridView1.EditIndex = e.NewEditIndex;
GetAllTest();
}
//Update
protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
TextBox adsoyad = new TextBox();
adsoyad = (TextBox)GridView1.Rows[e.RowIndex].Cells[4].Controls[0];
TextBox email = new TextBox();
email = (TextBox)GridView1.Rows[e.RowIndex].Cells[5].Controls[0];
CheckBox onay = new CheckBox();
onay = (CheckBox)GridView1.Rows[e.RowIndex].Cells[6].Controls[0];
bool durum=false;
if (onay.Checked) durum = true;
else durum = false;
ConnectionControl();
SqlCommand Cmd = new SqlCommand("UPDATE users SET adsoyad=@adsoyad,email=@email,status=@durum WHERE userID=@userId", myConnection);
Cmd.Parameters.Add("@adsoyad",SqlDbType.NVarChar).Value = adsoyad.Text;
Cmd.Parameters.Add("@email",SqlDbType.NVarChar).Value = email.Text;
Cmd.Parameters.Add("@durum",SqlDbType.Bit).Value = durum;
Cmd.Parameters.Add("@userId",SqlDbType.Int).Value = Convert.ToInt32(GridView1.Rows[e.RowIndex].Cells[3].Text);
cmd.ExecuteNonQuery();
DataSet Ds = new DataSet();
SqlDataAdapterDa = new SqlDataAdapter(SELECT * FROM AllTests, myConnection);
Da.Fill(Ds);
GridView1.EditIndex = -1;
GridView1.DataSource = Ds;
GridView1.DataBind();
con.Close();
}