Monday, 15 September 2014

c# - Displaying SQL Server database value in Gridview showing error -



c# - Displaying SQL Server database value in Gridview showing error -

when seek display database values in gridview error:

an unhandled exception of type 'system.data.sqlclient.sqlexception' occurred in system.data.dll

additional information: wrong syntax near keyword 'and'.

and code

private void button1_click(object sender, eventargs e) { sqldataadapter adap; dataset ds; sqlconnection cn = new sqlconnection( @"data source=dilipwin\sqlexpress;initial catalog=radb;integrated security=true"); cn.open(); var home = new home(); adap = new sqldataadapter( "select roll_num, mark marks mark < 50 , dept_id=" + home.cboxdept.selectedvalue + " , sem_id=" + home.cboxsem.selectedvalue + " , subject_id=" + home.cboxsubject.selectedvalue + " , batch_id= " + home.cboxbatch.selectedvalue + " , cls_id=" + home.cboxclass.selectedvalue, cn); ds = new system.data.dataset(); adap.fill(ds, "datagridview1"); datagridview1.datasource = ds.tables[0]; }

use sql-parameters solves issue , prevents future sql-injection issues:

string sql = @" select roll_num, mark marks mark < 50 , dept_id=@dept_id , sem_id=@sem_id , subject_id=@subject_id , batch_id=@batch_id , cls_id=@cls_id;"; dataset ds = new dataset(); using(var cn = new sqlconnection(@"data source=dilipwin\sqlexpress;initial catalog=radb;integrated security=true")) using (var da = new sqldataadapter(sql, cn)) { da.selectcommand.parameters.addwithvalue("@dept_id", home.cboxdept.selectedvalue ); da.selectcommand.parameters.addwithvalue("@sem_id", home.cboxsem.selectedvalue ); da.selectcommand.parameters.addwithvalue("@subject_id", home.cboxsubject.selectedvalue ); da.selectcommand.parameters.addwithvalue("@batch_id", home.cboxbatch.selectedvalue ); da.selectcommand.parameters.addwithvalue("@cls_id", home.cboxclass.selectedvalue ); da.fill(ds); // don't need open/close connection fill } datagridview1.datasource = ds.tables[0];

you should utilize right types. addwithvalue seek infer type value. if ints should parse them accordingly (int.parse(home.cboxdept.selectedvalue )).

c# sql sql-server gridview

No comments:

Post a Comment