How I can change rows places in datadridview? - c#

Good afternoon, dear developers.
Faced such a problem:
there is DataGridVev, I have data lines in it. Depending on the toss-up, I need to sort the order of the rows in the display.
How can I do that?
As I understand the lines do not have an index, and the columns have.
Here is my code for sorting
for(int i = 0; i < 9; i++)
{
int tmp = i;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
if ((string)row.Cells[2].Value == position[i])
{
Console.WriteLine(position[i] + "Место: " + tmp);
tmp += 9;
}
}
}
copied from the comment of the OP:
con = new SqlConnection();
con.ConnectionString = getConn;
con.Open();
adap = new SqlDataAdapter("SELECT * FROM " + table_name + " WHERE Groupe_year = #year ", con);
string year = comboBox1.Text;
adap.SelectCommand.Parameters.AddWithValue("#year", year);
ds = new System.Data.DataSet();
adap.Fill(ds, "Fighters_Details");
dataGridView1.DataSource = ds.Tables[0];

Assign the Data Source to a Data View instead.
dataGridView1.DataSource = ds.Tables[0].DefaultView;
For Sorting on the Groupe_year column as an example:
((System.Data.DataView)dataGridView1.DataSource).Sort = "Groupe_year";

Related

Adding data to data table without filling the column names C#

I am trying to add data from an excel spreadsheet to a data table, I am getting the data no worries and adding it to the tables within the datasets but when I do add it, it fills the column names with the top row. I have tried to set the column names but then it just cuts off the top row of data.
I am fairly new to C#, I'm pretty sure I need to alter the fill method objAdapter1.Fill(objDataset1,tableName); but have no idea how to go about it.
public DataSet readExcel()
{
int x = 0;
string[] Individal_Runs = Directory.GetFiles(#"C:\testfiles");
DataSet objDataset1 = new DataSet();
int iso = 0;
foreach (string s in Individal_Runs)
{
x++;
try
{
String theConnString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + s + ";Extended Properties=Excel 12.0 Xml";
OleDbConnection objConn = new OleDbConnection(theConnString);
objConn.Open();
string[] sheetnames = GetExcelSheetNames(String.Format("{0}", s));
int y = 0;
int z = 0;
string tableName;
bool looponce = false;
foreach (string sn in sheetnames)
{
OleDbCommand objCmdSelect = new OleDbCommand(String.Format("SELECT * FROM [{0}]", sn.ToString()), objConn);
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
if( looponce == false)
{
tableName = string.Format("isolations_{0}", iso);
objDataset1.Tables.Add(tableName);
objDataset1.Tables[tableName].NewRow();
DataRow newRow = objDataset1.Tables[tableName].NewRow();
objDataset1.Tables[tableName].Rows.InsertAt(newRow, 0);
looponce = true;
}
else
{
tableName = string.Format("isolations_{0}_{1}", iso,y);
objDataset1.Tables.Add(tableName);
DataRow newRow = objDataset1.Tables[tableName].NewRow();
objDataset1.Tables[tableName].Rows.InsertAt(newRow, 0);
y++;
}
objAdapter1.SelectCommand = objCmdSelect;
objAdapter1.Fill(objDataset1,tableName);
int cols = objDataset1.Tables[tableName].Columns.Count;
for (int i = 0; i < cols; i++)
{
objDataset1.Tables[tableName].Columns[i].ColumnName = i.ToString();
}
z++;
}
iso++;
}

How to split string and write them in different row in same datagridview c#

I have a database which include my computer's ids,users,old users etc.I fill my dataview perfectly.In my db I have a olduser column and it's look like ;
john;marry;tonny
And my other column "date" looks like ;
02.10.2018;05.09.2017;30.08.2015
So I want to see my datagridview like
PCNAME ID USER OLDUSER PLACE DATE
computer1 1 herry spain
computer1 1 john spain 02.10.2018
computer1 1 marry spain 05.09.2017
computer1 1 tonny spain 30.08.2015
When I write the code below it always give me
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
error
int i = 0;
public void firstdatagrid()
{
DataTable table = new DataTable();
dataGridView1.DataSource = table;
baglantı = new SqlConnection();
baglantı.ConnectionString = "Server=asdas;Database=asdsa;User Id=asdsa;password=asdaassad";
baglantı.Open();
komut = new SqlDataAdapter("SELECT * FROM TABLE WHERE PCID= '" + pcidcmbx.Text + "'", baglantı);
ds = new System.Data.DataSet();
komut.Fill(ds, "TABLE");
dataGridView2.DataSource = ds.Tables[0];
dataGridView2.Columns[0].HeaderText = "PCNAME";
dataGridView2.Columns[1].HeaderText = "ID";
dataGridView2.Columns[2].HeaderText = "USER";
dataGridView2.Columns[3].HeaderText = "OLD USER";
dataGridView2.Columns[4].HeaderText = "PLACE";
dataGridView2.Columns[5].HeaderText = "DATE";
foreach (DataGridViewRow row in dataGridView2.Rows)
{
names += row.Cells[3].Value;
dates += row.Cells[5].Value;
dataGridView2.Rows[0].Cells[3].Value = "";
dataGridView2.Rows[0].Cells[5].Value = "";
}
foreach (var a in names.Split(new char[] { ';' }))
{
MessageBox.Show(a.ToString());
DataRow newRow = table.NewRow();
table.Rows.Add(newRow);
dataGridView2.Rows[i].Cells[3].Value = a.ToString();
i = i + 1;
}
}
First of all you get this message because your values comes from db and when you try to add a new row manually,datagridview doesn't know what is come.
DataTable table = new DataTable();
DataGridView1.DataSource = table;
So try to use it will fix your problem I guess
DataTable dataTable = (DataTable)dataGridView2.DataSource;
DataRow drToAdd = dataTable.NewRow();
drToAdd[3] = a.ToString();
dataTable.Rows.Add(drToAdd);

Datagridview only adding 1 row

Im trying to add all my users accounts to a gridview but when using the foreach code it is only adding the last value of the datagridview. Is there a way to do all of them?
public DataTable GetResultsTable(string Username)
{
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
{
DataRow row = client.ExecuteQueryRow("SELECT * FROM users WHERE username = '" + Username + "'");
DataTable table = new DataTable();
table.Columns.Add("Username".ToString());
table.Columns.Add("Motto".ToString());
table.Columns.Add("Email".ToString());
table.Columns.Add("Homeroom".ToString());
table.Columns.Add("Health".ToString());
table.Columns.Add("Energy".ToString());
table.Columns.Add("Age".ToString());
DataRow dr = table.NewRow();
dr["Username"] = "" + row["username"] + "";
dr["Motto"] = "" + row["motto"] + "";
dr["Email"] = "" + row["mail"] + "";
dr["Homeroom"] = "" + row["home_room"] + "";
dr["Health"] = "" + row["health"] + "";
dr["Energy"] = "" + row["energy"] + "";
dr["Age"] = "" + row["age"] + "";
table.Rows.Add(dr);
return table;
}
}
SqlDatabaseManager.Initialize();
using (SqlDatabaseClient client = SqlDatabaseManager.GetClient())
foreach (DataRow row2 in client.ExecuteQueryTable("SELECT * FROM users").Rows)
{
dataGridView1.DataSource = GetResultsTable((string)row2["username"]);
}
The DataSource property of a DataGridView object shouldn't be one row, but many.
So you can change your code to create a list first and apply this as the DataSource, OR you use the following method:
dataGridView1.Rows.Add(GetResultsTable(row2["username"].ToString());
In the foreach loop.
Hope it helps you out :).
you can use one method to load the data
public DataTable fillDataTable()
{
// select all the columns with expected column name, here I only added 3 columns
string query = "SELECT username as Username, motto as Motto, mail as Email FROM users;
using(SqlConnection sqlConn = new SqlConnection(conSTR))
using(SqlCommand cmd = new SqlCommand(query, sqlConn))
{
sqlConn.Open();
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
return dt;
}
}
set the grid DataSource like below
dataGridView1.DataSource =fillDataTable();

C# All rows from MySQL query not going into datagridview

Im trying to fill a DataGridView with the results from a MySql Query however they are not all going in. Here is my code:
try
{
conn.Open();
player_search = new MySqlCommand("SELECT * FROM admin;", conn);
reader = player_search.ExecuteReader();
int counter = 0;
while (reader.Read())
{
player_list[0, counter].Value = reader.GetString(0);
player_list[1, counter].Value = reader.GetString(1);
player_list[2, counter].Value = reader.GetString(6);
player_list[3, counter].Value = reader.GetString(7);
player_list[4, counter].Value = reader.GetString(8);
player_list[5, counter].Value = reader.GetString(9);
player_list[6, counter].Value = "Remove";
counter = counter+1;
}
}
However it doesnt all go in. It only inserts the first row of the query? Why is it doing this? Im getting no errors?
Solved it! I had to do a long winded approach but it works!
MySqlCommand mysqlcmd = new MySqlCommand("SELECT * FROM admin;", conn);
MySqlDataAdapter mysqlad = new MySqlDataAdapter(mysqlcmd);
DataSet ds = new DataSet();
mysqlad.Fill(ds);
DataTable dt = ds.Tables[0];
player_list.DataSource = dt;
int rowIndex = 0;
foreach (DataRow row in dt.Rows)
{
int i = 0;
foreach (var item in row.ItemArray)
{
if (i == 0) {
player_list[0, rowIndex].Value = item.ToString();
}
if (i == 1) {
player_list[1, rowIndex].Value = item.ToString();
}
if (i == 4)
{
player_list[2, rowIndex].Value = item.ToString();
}
if (i == 7)
{
player_list[3, rowIndex].Value = item.ToString();
}
if (i == 8)
{
player_list[4, rowIndex].Value = item.ToString();
}
if (i == 9)
{
player_list[5, rowIndex].Value = item.ToString();
}
player_list[6, rowIndex].Value = "Remove";
++i;
}
++rowIndex;
i = 0;
}
I would suggest you to try to get it using DataSet:
public DataTable GetDBDataTable(MySqlConnection dbconnection, string table, string columns = "*", string clause = "")
{
MySqlCommand mysqlcmd = new MySqlCommand("SELECT " + columns + " FROM " + table + " " + clause +";", dbconnection);
MySqlDataAdapter mysqlad = new MySqlDataAdapter(mysqlcmd);
DataSet ds = new DataSet();
mysqlad.Fill(ds);
DataTable dt = ds.Tables[0];
return dt;
}
UPDATE: player_list.DataSource(GetDBDataTable(...));
player_list.DataBind();

10 random rows from excel

Help me with my code, because i don't now how to do this simple task. How to select 10 random rows from excel file?
string filepath = #"C:\1.xlsx";
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + #";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text""";
OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]", conn);
DataSet ds = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
adapter.Fill(ds);
showdata.DataSource = ds.Tables[0];
If you create a DataGridView on your Windows Form called RandomExcelRows, create a button called button1 and put the following code inside the Click event handler for button1:
private void button1_Click(object sender, EventArgs e)
{
Excel.Range[] rows = RandomRows(10, #"C:\test\whatever.xlsx");
DataTable dt = new DataTable();
bool ColumnsCreated = false;
foreach(Excel.Range row in rows)
{
object[,] values = row.Value;
int columnCount = values.Length;
if(!ColumnsCreated)
{
for(int i = 0; i < columnCount; i++)
{
DataColumn dc = new DataColumn(String.Format("Column {0}", i));
dt.Columns.Add(dc);
ColumnsCreated = true;
}
}
DataRow dr = dt.NewRow();
for (int i = 0; i < columnCount; i++)
{
dr[String.Format("Column {0}", i)] = values[1,i+1];
}
dt.Rows.Add(dr);
}
RandomExcelRows.DataSource = dt;
}
And then create a method underneath called RandomRows containing the following:
private Excel.Range[] RandomRows(int randomRowsToGet, string worksheetLocation, int worksheetNumber = 1, int lowestRow = 0, int highestRow = 99)
{
Excel.Range[] rows = new Excel.Range[randomRowsToGet];
Excel.Application excel = new Excel.Application();
Excel.Workbook workbook = excel.Workbooks.Open(worksheetLocation);
Excel.Worksheet worksheet = workbook.Worksheets[worksheetNumber];
List<int> rowNumbers = new List<int>();
bool allUniqueNumbers = false;
Random random = new Random();
while (!allUniqueNumbers)
{
int nextNumber = random.Next(lowestRow, highestRow);
if (!rowNumbers.Contains(nextNumber))
rowNumbers.Add(nextNumber);
if (rowNumbers.Count == randomRowsToGet)
allUniqueNumbers = true;
}
for (int i = 0; i < randomRowsToGet; i++)
{
rows[i] = worksheet.UsedRange.Rows[rowNumbers[i]];
}
Marshal.ReleaseComObject(excel);
return rows;
}
The program will take a random number of rows (this amount is specified by you) from the Spreadsheet you specify and place these rows into your DataGridView.
It's pretty crude, and needs refactoring but it is the basis of what you need. You could also get the string containing the file location from a textbox instead of hardcoding this, the same goes for the number of rows you want, and the other parameters such as minimum and maximum rows.
As well, you could use an OpenFileDialog to allow your user to browse to your excel file, etc etc.
Here is my solution:
string filepath = #"C:\1.xlsx";
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filepath + #";Extended Properties=""Excel 12.0 Xml;HDR=YES;IMEX=1;TypeGuessRows=0;ImportMixedTypes=Text""";
OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]", conn);
DataSet ds = new DataSet();
OleDbDataAdapter adapter = new OleDbDataAdapter(command);
adapter.Fill(ds);
// above code block is yours as is.
// below part is for sorting.
DataTable data = ds.Tables[0];
data.Columns.Add(new DataColumn("Guid"));
for (int i = 0; i < data.Rows.Count; i++)
{
data.Rows[i].SetField("Guid", Guid.NewGuid());
}
DataView dv = data.DefaultView;
dv.Sort = "Guid desc";
showdata.DataSource = dv.ToTable();

Categories