6

As I know char is different from string. I give datatype char to a column status in a table. I am stuck here because i am using char first time. here is my code

 cmd.CommandType = CommandType.StoredProcedure;
        if (con.State == ConnectionState.Closed)
            con.Open();
        MySqlDataReader dr = cmd.ExecuteReader();
        List<clssessionprp> obj = new List<clssessionprp>();
        while (dr.Read())
        {
            clssessionprp k = new clssessionprp();
            k.p_sescod = Convert.ToInt32(dr[0]);
            k.p_session = dr[1].ToString();
            k.p_status = dr[2].ToString();
        }

here status column is of char datatype. I google this but can't found any desired result. any help will be appriciated

my BLL code is

public void save_rec(clsclsprp p)
    {
        MySqlCommand cmd = new MySqlCommand("ins_cls", con);
        cmd.CommandType = CommandType.StoredProcedure;
        if (con.State == ConnectionState.Closed)
            con.Open();
        cmd.Parameters.Add("_clsnam", MySqlDbType.VarChar, 50).Value = p.p_clsnam;
        cmd.Parameters.Add("_clsdes", MySqlDbType.VarChar, 200).Value = p.p_clsdes;
        cmd.Parameters.Add("_clssec", MySqlDbType.Char,1).Value = p.p_clssec;
        cmd.ExecuteNonQuery();
        con.Close();
        cmd.Dispose();
    }

4 Answers4

9

You can use Convert.ToChar(Object) to directly converting object to character instead of converting it to string using ToString().

k.p_status = Convert.ToChar(dr[2]);
Adil
  • 146,340
  • 25
  • 209
  • 204
  • one more question adil, Char is not supported in mysqldbtype than should we change it or how to fix it ? –  Jan 16 '14 at 08:56
  • Do you get exception when you execute Convert.ToChar(dr[2]) ? what data it contains? – Adil Jan 16 '14 at 08:58
  • It work fine but when pass parameter in any method in my BLL. It says 'MySqlDbType does not contain a definition for Char' I am using Mysql with asp.net webforms –  Jan 16 '14 at 09:02
  • What if you convert char to string before you pass to MySQLDb or using some other appropriate type instead of string? – Adil Jan 16 '14 at 09:11
  • Can you try this, cmd.Parameters.Add("_clssec", MySqlDbType.String).Value = p.p_clssec.ToString(); – Adil Jan 16 '14 at 09:25
  • it gives me no error but my char has size 1. is it correct to use String ? –  Jan 16 '14 at 09:34
3

How about:

dr[2].ToString()[0] - checking that it is not null, of course.

Alternatively:

Convert.ToChar(dr[2]) could work too.

MZimmerman6
  • 8,445
  • 10
  • 40
  • 70
tofutim
  • 22,664
  • 20
  • 87
  • 148
2

There are two options...

Convert.ToChar(dr[2]);

or

char chartext = text.ToCharArray()[0];

user2463514
  • 273
  • 1
  • 4
  • 19
0

What about this

   k.p_status  = char.Parse(dr[2].ToString());
Nilesh Gajare
  • 6,302
  • 3
  • 42
  • 73