c# - Selecting Random record in a datagridview -


i have got datagrid view in windows form project is filled data.. have button (nextbutton) clicked go through these records. there way can select random record datagrid view whenever next button clicked.

this code fills datagridview.

  sqlconnection conn = new sqlconnection(connection);         sqlcommand db = new sqlcommand("select * tblemp emp_title = 'mr'", conn);         sqlcommandbuilder builder = new sqlcommandbuilder(dataadapter);         dataadapter = new sqldataadapter(db);         dataset = new dataset();         dataadapter.fill(dataset, "tblemp");         datagridview1.datasource = dataset.tables["tblemp"]; 

and here code nextbutoon goes through records

void nextrecord() {     if ( recordcounter; dataset.tables[0].rows.count -1)     {         recordcounter++;         txtdisplayquestion.text = dataset.tables[0].rows[ recordcounter][emp_title].tostring();     } } 

thank you

this trick. avoid selecting same row twice, method remembers last selected row , tries find new random row if same row selected second time.

private random rnd = new random(); private int lastselectedindex = -1;  void randomrecord() {     int norows = dataset.tables[0].rows.count;     int index = rnd.next(norows);      while(index == lastselectedindex && norows > 1) {         index = rnd.next(norows);     }      lastselectedindex = index;      txtdisplayquestion.text = dataset.tables[0].rows[index][emp_title].tostring(); } 

Comments

Popular posts from this blog

android - Get AccessToken using signpost OAuth without opening a browser (Two legged Oauth) -

org.mockito.exceptions.misusing.InvalidUseOfMatchersException: mockito -

google shop client API returns 400 bad request error while adding an item -