How to remove header name / column name from datatable - c#

I only want data not header column names from the DataTable result set. or is it possible to create a DataTable without column headers. i tried every possible scenario but couldn't get anything.
above
Is my sp result, which I can very easily convert into DataTable. But I don't want to header row. there is option in SQL where we can include or exclude the column headers but even that is not working
Your help is highly appreciated.
this is my test c# code
DataTable table = new DataTable();
SqlCommand cmd = new SqlCommand("Rmtest1", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#unitName", SqlDbType.VarChar).Value = unitName;
cmd.Parameters.Add("#startdate", SqlDbType.VarChar).Value = startDate;
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(table);
So basically I want the rows but not the headers

As far as I know, you cant hide/remove the column header, but you can change the column header name with some string space (" ") to make the column header looks like blank.

You can't hide column header from DataTable. But you can hide it from your displaying control. I'm not sure which control you want to use for your case, but you can use the following code to hide it from DataGridView in WinForm App.
dgwStudents.ColumnHeadersVisible = false;

Related

C# how to copy datagridview's currentrow to single datarow?

DataRow dr;
dr = ((dgv.DataSource) as DataTable).Rows[dgv.CurrentRow.Index];
dgv is DataGridView predefined on winform.
dr is single always.
Above code was found.
But it doesn't work right. Because CurrentRow.Index is not macthed to DataTable's Index.
I think to copy DataGridViewRow to DataRow is simplest way. Is it impossible?
Reason trying this is for Update to/Delete from database when dgv is changed. Any other better solution for remote DB CRUD from local dgv should be great.
Thanks in advance.
You can link you datagridview directly to your database table without passing by the datatable by defining an ID column in the database table (you can either display or not the ID column in the datagridview) as shown bellow
Code behind:
SqlCommand update = new SqlCommand();
update.connection = conn; // conn is your SqlConnection to the server
update.parameters.add("#Id",[sqldbtype.int]).value=dgv.Rows[dgv.CurrentRow.Index].Cell[0]; // 0 is the cell index of the ID column
update.Commandtext="Delete from table where [ID]=#ID" // delete the selected row
conn.open();
update.ExecuteNonQuery();
SqlDataAdapter adapter = SqlDataAdapter("SELECT*FROM Table", conn);
conn.close();
Datatable table = new Datatable();
adapter.Fill(table);
dgv.Datasource = table.Items;

ComboBox remaining blank after selected value

I am writing a small application in C# using windows forms. I have a combo box that I am populating by querying a database for column names to use as the values inside the combo box. My code currently can get the values just fine, however whenever I click on the combo box it removes any text and just displays a blank 'selected option'. I have tried multiple things to correct this (changed the database field from char to varchar), tried binding to a different dataset etc. but nothing has worked. Ive also looked at other posts on this such as
C# comboBox databinding - nothing happens, then it goes back to blank
Below is my code, and I believe I am doing the displaymember/valuemember part wrong however I do not understand what it is that is wrong. The column name in the database is Reason and it consists of 3 values.
Any help is appreciated.
String ConnString = ConfigurationManager.ConnectionStrings["Portal1"].ConnectionString;
SqlConnection conn = new SqlConnection(ConnString);
conn.Open();
SqlCommand sc = new SqlCommand("select [Reason] from tblReasons", conn);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("Reason", typeof(string));
dt.Load(reader);
cboxReason.ValueMember = "Reason";
cboxReason.DisplayMember = "Reason";
cboxReason.DataSource = dt;
conn.Close();
Your code looks OK. I would not add the column, that should happen automatically. Here is my sample code that works:
SqlConnection conn = new SqlConnection(ConnString);
conn.Open();
var reader = new SqlCommand("select ID from Users", conn).ExecuteReader();
DataTable dt = new DataTable();
dt.Load(reader);
comboBox1.ValueMember = "ID";
comboBox1.DisplayMember = "ID";
comboBox1.DataSource = dt;
conn.Close();
Note: This populates with the list of values in the column. For the list of column names, I would suggest changing your query to return a list of columns for the table (DB specific query) OR look at the DataTable.Columns collection for the column names.
Did you try the answer from C# - Fill a combo box with a DataTable
cboxReason.BindingContext = this.BindingContext;

DataSet showing name only and not table data c#

In my c# code I am trying to create an excel report with my data. I was trying some way to give my data headers. So I called my stored procedure added my dataset tables and now I want to add one of those tables to be a row in my data table. It returns one row my dataset does. example of how I want it to look:
Title
93.76% 00:23:59 00:33:41 95.56% 00:57:40 94.66%
Seems simple enough that's why I choose datatable to do so with and not dataset because I was limited to the dataset tables formatting. How can I get my data table to display the the data and not the name? Code provided below. I am also up for any other suggestions on how to accomplish this. If you need any more info or code please feel free to ask.
var dt = new DataTable("IncomingProductReport");
dt.Columns.Add("A Line Down Time");
SqlCommand cmd = new SqlCommand("L_GetTimeTotals", conn);
cmd.Parameters.Add("#startTime", SqlDbType.DateTime, 30).Value = RadDateTimePicker2.SelectedDate;
cmd.Parameters.Add("#endTime", SqlDbType.DateTime, 30).Value = RadDateTimePicker3.SelectedDate;
cmd.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(cmd);
var ds = new DataSet();
ds.Tables.Add("IncomingProductTotals");
ds.Tables.Add("IncomingProductTotalsA");
ds.Tables.Add("IncomingProductTotalsB");
ds.Tables.Add("IncomingProductTotals1");
ds.Tables.Add("IncomingProductTotalsA1");
ds.Tables.Add("IncomingProductTotalsB1");
da.TableMappings.Add("Table", "IncomingProductTotals");
da.TableMappings.Add("Table1", "IncomingProductTotalsA");
da.TableMappings.Add("Table2", "IncomingProductTotalsB");
da.TableMappings.Add("Table3", "IncomingProductTotals1");
da.TableMappings.Add("Table4", "IncomingProductTotalsA1");
da.TableMappings.Add("Table5", "IncomingProductTotalsB1");
da.Fill(ds);
ds.Tables.Remove("IncomingProductTotalsA");
ds.Tables.Remove("IncomingProductTotalsB");
ds.Tables.Remove("IncomingProductTotalsA1");
ds.Tables.Remove("IncomingProductTotalsB1");
dt.Rows.Add("Line 1 Totals");
dt.Rows.Add(ds.Tables["IncomingProductTotals"]);
dt.Rows.Add("Line 2 Totals");
dt.Rows.Add(ds.Tables["IncomingProductTotals1"]);
ExcelHelper.ToExcel(dt, "DownTimeTotals.xls", Page.Response);
dt.Columns.Add("A Line Down Time");
You are adding a Column to the DataTable. You do not say what type so it will be the default type and that is string.
dt.Rows.Add(ds.Tables["IncomingProductTotals"]);
Then you try to put a complete DataTable into a cell of a Column that expects strings. To get a string from the given object the system will call the ToString method of the DataTable. And ToString is implemented as returning the Tablename of a DataTable.
You need to take the data in the DataTables to put into the dt DataTable not the DataTables itself. That makes no sense. Allowed types for a column if you really wanted to put a DataTable into a DataTable are only the once described here.

How to get the values from Access Database and set in Gridview in C# winforms Devexpress?

I have Gridview (gridview1), some TextEdits in the Form and add some Data's to few rows and i stored the gridview1 Data's and textedits to Access Database. In another form i Bind some column to gridview1 and TextEdits to new Gridview (gridview2). Now if i click edit button on any row in the gridview2, I want to get the Data's from Access Database and shown in 1st Form gridview1 and textedits fill automatically recording to Focused Row cell unique value.
Using this code i get value to TextEdits Fields
OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/Srihari/OrionSystem.accdb");
OleDbCommand da = new OleDbCommand("select * from invoice_top where invoice_number=" + textEdit5.Text, con);
con.Open();
OleDbDataReader reader = da.ExecuteReader();
while (reader.Read())
{
textEdit12.Text = reader.GetValue(1).ToString();
textEdit13.Text = reader.GetValue(2).ToString();
textEdit4.Text = reader.GetString(3);
dateEdit1.Text = reader.GetValue(8).ToString();
textEdit1.Text = reader.GetValue(5).ToString();
textEdit2.Text = reader.GetValue(6).ToString();
textEdit3.Text = reader.GetValue(7).ToString();
checkEdit1.Checked = reader.GetBoolean(4);
}
con.Close();
I also want to fill gridview Data's ? I tried this bus its not working
gridView1.SetRowCellValue(gridView1.FocusedRowHandle, gridView1.Columns[2], reader1.GetString(2));
How to set Access Database values to grdiview ?? Please Help me ?
Thanks in Advance.
I think you need to read a tutorial on Data Binding.
The GridControl can be bound to a data source which implements IList<>, IBindingList<> or IQueryable<> simply by setting the GridControl.DataSource property. There is no need to loop through your recordset and set the value for each row/cell individually. Additionally, I would suggest you Data Bind your TextEdit controls (to the EditValue property, NOT the Text property) rather than manually setting them like you are doing above.
This code is VB.NET but the ideea is the same in C#
Dim SIRCON as string = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/Srihari/OrionSystem.accdb"
Using con As New OleDbConnection(SIRCON)
con.Open()
Dim strSQL As String = "select * from invoice_top where invoice_number=" + textEdit5.Text
dim dt as new datatable
dt.Load(New OleDbCommand(strSQL, conexiune).ExecuteReader())
conexiune.Close()
GridControl1.datasource = dt
GridControl1.ForceInitialise
End Using

updating the values in database from datagridview

i want to create a for loop in which i want to write a query which updates the the value of each row in database. the rows are present in the datagridview as well as in the database. the aim is when the changes are made in datagridview so using a button the change are also applied in the database table too. in each row the barcode and its quantity is different. if the changes are made in all the rows in datagridview so it is also to be applied in database using button and also please help with the parameters.
here is the query which should be considered in the for loop:
SqlCommand cmd2 = new SqlCommand("update prod_info set item_quantity=#qty where barcode=#barcode ", con);
consider barcode as column1 and item_quantity as column2.
so far to create a for loop i have tried this but getting error in the for loops:
for (int i = 0; dataGridView2.Rows.Count; i++) //getting error here
{
SqlCommand cmd2 = new SqlCommand("update prod_info set item_quantity=#qty where barcode=#barcode ", con);
cmd2.Parameters.AddWithValue("#barcode", dataGridView2.Rows[i].Cells[1].Value.ToString());
cmd2.Parameters.AddWithValue("#qty", dataGridView2.Rows[i].Cells[1].Value.ToString());
}
you should call cmd2.ExecuteNonQuery(); in your loop ... otherwise no sql commands will be executed
to get a better solution you should move to creation of cmd2 before the loop. also add the parameters there (without assigning values) ... inside the loop just assign the values and call ExecuteNonQuery.
maybe the best solution would be to use databinding and a SqlDataAdapter with assigned UpdateCommand.
just saw that there probably is an error in your code ... you use the value from Cell[1] for both of your parameters ...
example:
first create a DataTable ... var dt = new DataTable();
then add the columns you want in your grid to the DataTable ... dt.Columns.Add("xyz");
then attach the DataTable to your grid: dataGridView2.DataSource = dt;
now you should be able to edit the contents of column "xyz". to write the values to the database you create a SqlDataAdapter ... var adp = new SqlDataAdapter();
then set adp.InsertCommand = new SqlCommand(...) and adp.UpdateCommand = new SqlCommand(...)
now you can call adp.Update(); and all the values from your grid are written to db ... for newly added rows the InsertCommand is invoked and for edited rows the UpdateCommand is invoked.

Categories

Resources