none
can some one help to my problem RRS feed

  • Question

  •  i am trying to read a Id value and pass it to the above function.
     
     DBFun.GetnameById(

    "Addr", "Name", Acc.AccConn, "Addr_id",Id);


    the function defination for the GetnamebyId  is:

    public

    string GetnameById(string tblname, string fldname, System.Data.SqlClient.SqlConnection conn, string fldId,string Id)

    {

     

    string sql;

     

    string nameid;

    sql =

    " select * from " + tblname ;

    sql = sql +

    " where ("+fldId+")= " + Id;

     

     

    sqlcmd =

    new System.Data.SqlClient.SqlCommand(sql, conn);

    nameid =

    "";

     

    try

    {

    sqlRead = sqlcmd.ExecuteReader();

     

    while (sqlRead.Read())

    {

    nameid = (sqlRead[fldname].ToString());

    sqlcmd.Dispose();

    sqlRead.Dispose();

    }

    }

     

    catch (SystemException ex)

    {

     

    Console.WriteLine(ex.Message);

    }

     

    return (nameid);

    }

    Friday, August 14, 2009 1:06 PM

Answers

  • Hi,

    You didnt say what error you are getting or what problem you ar having!!

    If you would like I have modified your function,
    public string GetnameById(string tblname, string fldname, System.Data.SqlClient.SqlConnection conn, string fldId, string Id)
            {
                string Name = string.Empty;
                string Query = "SELECT " + fldname + " FROM " + tblname + " WHERE " + fldId + " = '" + Id + "'";
                using (SqlCommand oSqlCommand = new SqlCommand(Query, conn))
                {
                    using (SqlDataReader oSqlDataReader = oSqlCommand.ExecuteReader())
                    {
                        if (oSqlDataReader.HasRows)
                        {
                            while (oSqlDataReader.Read())
                            {
                                Name = Convert.ToString(oSqlDataReader[fldname]);
                                break;
                            }
                        }
                    }
                }
                return Name;
            }



    Regards,
    Vinil;
    • Marked as answer by Yichun_Feng Thursday, August 20, 2009 4:05 AM
    Friday, August 14, 2009 2:48 PM