Hi Guys,
I'm trying to make validation for record data exist or not in database, before everything running as well, but somehow the code always return value "Data not found" even though data exists on database.
What gone wrong with this code?
Anny help could be appreciate.
Code bihind
protected void btnAddCariAnggota_Click(object sender, EventArgs e)
{
CariNamaAnggota();
}
private void CariNamaAnggota()
{
string id_anggota = txtid_anggota.Text.Trim();
using (SqlConnection cn = new SqlConnection(koneksi))
{
using (SqlDataAdapter da = new SqlDataAdapter())
{
using (SqlCommand cmd = new SqlCommand("SPCariNamaAnggota",cn))
{
try
{
DataSet ds = new DataSet();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@id_anggota", id_anggota);
//cmd.CommandText = "Select nama_anggota From tbl_anggota Where id_anggota=@id_anggota";
da.SelectCommand = cmd;
cn.Open();
da.Fill(ds);
cn.Close();
if (ds.Tables[0].Rows.Count == 0)
{
// If ds has no value (no record) show error
Response.Write("<script>alert('Data not found !!!')</script>");
}
else
{
//If record exists
using (SqlCommand sqlcmd = new SqlCommand("SPCariNamaAnggota"))
{
cn.Open();
sqlcmd.Connection = cn;
sqlcmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adp = new SqlDataAdapter(sqlcmd);
SqlParameter param = new SqlParameter("@id_anggota", id_anggota);
sqlcmd.Parameters.Add(param);
using (SqlDataReader rdr = sqlcmd.ExecuteReader())
{
while (rdr.Read())
{
txtnama_anggota.Text = rdr["nama_anggota"].ToString();
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
}
}
}
The Store Prosedure
CREATE PROCEDURE [dbo].[spCariNamaAnggota]
@id_anggota varchar(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
Select nama_anggota From dbo.tbl_anggota Where id_anggota = @id_anggota
END