Cannot implicitly convert type 'int' to 'string' ? c#4 [closed]

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-17 23:21:46

问题


while running the given below code, getting an error. I have to perform delete operation through gridview.

code:

protected void gvEdit_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string Emp_ID = gvEdit.DataKeys[e.RowIndex].Value.ToString();

        int EId = Convert.ToInt32(Emp_ID); // error popup here
        ShadingAnalysisDataSetTableAdapters.tbl_EmployeeToTeamTableAdapter tm;
        tm = new ShadingAnalysisDataSetTableAdapters.tbl_EmployeeToTeamTableAdapter();
        DataTable dt = new DataTable();
        tm.GetDelete(EId);
        BindData();
    }

DB:

SQL:

DELETE FROM tbl_EmployeeToTeam WHERE (Emp_ID = @Emp_ID)

回答1:


I assume that GetDelete expects a string but you're passing an int. I think so because it seems to be the parameter for Emp_ID which is a varchar. So you could simply pass that string which you already had in:

gvEdit.DataKeys[e.RowIndex].Value.ToString();

But if it's supposed to be an int, why don't you use the correct data type in the database?

Bad habits to kick : choosing the wrong data type

Update

My employee Id is strating from EMP001, EMP002..etc. So how can I use integer data type

Why do you store always EMP at the beginning? You could also omit that and use int as type which would be more efficient and fail-safe. Then you could prepend EMP where you need to display it.

However, if you don't want to change that and Emp_ID contains only the ID without EMP you can use string concatenation:

tm.GetDelete("EMP" + Emp_ID);


来源:https://stackoverflow.com/questions/26839755/cannot-implicitly-convert-type-int-to-string-c4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!