Create function GetAllChechedBox with text and value and insert in new DataTable - c#

I want to take the text and value from selected and not selected elements from CheckBoxList and insert in datatable
MultiCheckCombo Reference
Now I want to get text and value from this checklist,
I think it would be comfortable to place in a DataTable
public DataTable GetAllChechedBox()
{
var dt = new DataTable();
for (int i = 0; i < chkList.Items.Count; i++)
{
if (chkList.Items[i].Selected)
{
dt.Columns.Add("Name");
dt.Columns.Add("Value");
// how add all checked with value and text in this datatable?
}
}
return dt;
}
/also want to take a function with text and value for unselected elements/

Instead of chkList.Items[i].Selected, use chkList.Items[i].Checked....plus
add column outside loop
public DataTable GetAllChechedBox()
{
var dt = new DataTable();
dt.Columns.Add("Name");
dt.Columns.Add("Value");
for (int i = 0; i < chkList.Items.Count; i++)
{
if (chkList.Items[i].Checked)
{
dt.Rows.Add();
dt.Rows[dt.Rows.Count-1]["Name"] = chkList.Items[i].Value;
dt.Rows[dt.Rows.Count-1]["Value"] = chkList.Items[i].Text;
}
}
return dt;
}

Related

I have two datagridview, one on the staff calls, I want to make the other contain the number of staff did the call

The following images show my two datagrid views
From what I understand from your question, you can use the following method
public DataTable numOfCalls(DataTable table)
{
//Initialize Result Table
DataTable numOfCallsTable = new DataTable();
numOfCallsTable.Columns.Add("agentName", typeof(string));
numOfCallsTable.Columns.Add("numOfCall", typeof(int));
// Get the unique agents
DataView view = new DataView(table);
DataTable distinctValues = view.ToTable(true, "agentName");
// Check if there are agents
if (distinctValues.Rows.Count > 0)
{
// Loop thru the agents
for (int i = 0; i < distinctValues.Rows.Count; i++)
{
string agentName = distinctValues.Rows[i]["agentName"].ToString();
// Get all the rows that this agent has
DataRow[] agentRows = table.Select($"agentName='{agentName}'");
// And then fill the second table
DataRow newRow = numOfCallsTable.NewRow();
newRow["agentName"] = agentName;
newRow["numOfCall"] = agentRows.Length;
numOfCallsTable.Rows.Add(newRow);
}
}
return numOfCallsTable;
}
You can call this method every time you add or delete a line to the first table.
update for the button that you asked
private void Button1_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable();
dt = (DataTable)dataGridView1.DataSource;
dataGridView2.DataSource = numOfCalls(dt);
}

how to map object to datatable row for displaying in datagrid?

Here is a function to set the value to a custom object from DB resultset, and then i want to return a datatable again.
public DataTable getProductsTable(DataSet productData)
{
DataTable dt = new DataTable();
try
{
int i = 0;
dt.Columns.Add("catid", typeof(string));
for (i = 0; i <= productData.Tables[0].Rows.Count - 1; i++)
{
productData dataObj = new productData();
dataObj.id = (string)productData.Tables[0].Rows[i]["id"].ToString();
dataObj.barcode = (string)productData.Tables[0].Rows[i]["barcode"].ToString();
dataObj.catid = (string)productData.Tables[0].Rows[i]["catid"].ToString();
dataObj.entity_id = (string)productData.Tables[0].Rows[i]["entity_id"].ToString();
dataObj.sku = (string)productData.Tables[0].Rows[i]["sku"].ToString();
dataObj.name = (string)productData.Tables[0].Rows[i]["name"].ToString();
dataObj.price = (string)productData.Tables[0].Rows[i]["price"].ToString();
dataObj.final_price = (string)productData.Tables[0].Rows[i]["final_price"].ToString();
dataObj.qty = (string)productData.Tables[0].Rows[i]["qty"].ToString();
dataObj.is_in_stock = (string)productData.Tables[0].Rows[i]["is_in_stock"].ToString();
dataObj.special_from_date = (string)productData.Tables[0].Rows[i]["special_from_date"].ToString();
dataObj.special_to_date = (string)productData.Tables[0].Rows[i]["special_to_date"].ToString();
dataObj.status = (string)productData.Tables[0].Rows[i]["status"].ToString();
dataObj.parent_id = (string)productData.Tables[0].Rows[i]["parent_id"].ToString();
dataObj.type_id = (string)productData.Tables[0].Rows[i]["type_id"].ToString();
//data.Add(dataObj);
dt.Rows.Add(dataObj);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return dt;
}
But it does not work, after i run above function, all columns are displayed but all rows are not displayed with no value, the first column only display namespace.productData. Anyone how to fix this?
https://s27.postimg.org/li3lmr99f/test.png
dt has only one column ("catid"). Add more columns for each property like below :
DataTable dt = new DataTable()
{
Columns = { "id", "barcode", "catid", etc...}
};
DataTable.Rows is of type DataRowCollection which has 2 overloads of Add method:
1. public void Add(DataRow row)
2. public DataRow Add(params object[] values)
dt.Rows.Add(dataObj); uses the second overload and adds a single value in the first column. To add values correctly use
dt.Rows.Add(dataObj.id, dataObj.barcode, etc... );

Why conversion from Gridview to datatable fails?

I have been trying to convert GRIDVIEW to DataTable but it doesn't give me data, it only gives me HEADERS of GridView but not the data inside it. Why ? I am using template fields in gridview
Calling it from event:
DataTable dt = GetDataTable(GridView DenominationsWiseTransactions);
Conversion function:
DataTable GetDataTable(GridView dtg)
{
DataTable dt = new DataTable();
// add the columns to the datatable
if (dtg.HeaderRow != null)
{
for (int i = 0; i < dtg.HeaderRow.Cells.Count; i++)
{
dt.Columns.Add(dtg.HeaderRow.Cells[i].Text);
}
}
// add each of the data rows to the table
foreach (GridViewRow row in dtg.Rows)
{
DataRow dr;
dr = dt.NewRow();
for (int i = 0; i < row.Cells.Count; i++)
{
dr[i] = row.Cells[i].Text.Replace(" ", "");
}
dt.Rows.Add(dr);
}
return dt;
}
So, when you are looping through the rows in the datagrid, it will include headers, the rows and the footer.
To see just the data rows you need to do something like:
if (e.Row.RowType == DataControlRowType.DataRow)
{ //convert that row }
Your conversion line might need some work, but at least you'll only need to concern yourself with datarows now.

How I write to the file from datagridview

Am trying to write from the datagridview with a goal of saving the input to the xml file, but am not getting it correctly. My code:
XDocument doc = XDocument.Load(outputFilePath);
doc.Save(outputFilePath);
oDataSet = new DataSet();
foreach (DataGridViewRow _rows in Gridview_Output.Rows)
{
DataRow oDatarow = oDataTable.NewRow();
for (int i = 0; i < Gridview_Output.ColumnCount; i++)
{
oDataTable.Rows.Add(oDatarow.ItemArray);
}
}
oDataSet.Tables.Add(oDataTable);
oDataSet.WriteXml(outputFilePath);
doc.Save(outputFilePath);
I want to write to this empty tags:
<data name="Exit_Button" xml:space="preserve">
<value></value>
<comment>[Font][/Font][DateStamp][/DateStamp][Comment][/Comment]</comment>
</data>
Hmm try this to create a datatable from gridview:
private DataTable GetDataTableFromDGV(DataGridView dgv) {
var dt = new DataTable();
foreach (DataGridViewColumn column in dgv.Columns) {
if (column.Visible) {
// You could potentially name the column based on the DGV column name (beware of dupes)
// or assign a type based on the data type of the data bound to this DGV column.
dt.Columns.Add();
}
}
object[] cellValues = new object[dgv.Columns.Count];
foreach (DataGridViewRow row in dgv.Rows) {
for (int i = 0; i < row.Cells.Count; i++) {
cellValues[i] = row.Cells[i].Value;
}
dt.Rows.Add(cellValues);
}
return dt;
}
Then you can do:
DataTable dT = GetDataTableFromDGV(DataGridView1);
DataSet dS = new DataSet();
dS.Tables.Add(dT);
dS.WriteXml(File.OpenWrite("xml.xml"));

SQL query to DataTable to include headers

Up until now, I had a utility class that contained a function called "getTable", which took a string query and returned a datatable. Now I'm trying to get these queries to be returned via excel. Simply copying the contents of the datatable to excel works fine - however there's no header row on the spreadsheet to explain what each column is.
Below is my attempt:
public static DataTable getTable(String sql, bool includeHeaderRow)
{
DataTable table = new DataTable();
using (SqlDataAdapter adpt = new SqlDataAdapter(sql, getConn()))
{
adpt.Fill(table);
if (includeHeaderRow)
{
DataRow headerRow = table.NewRow();
for (int i = 0; i < table.Columns.Count; i++)
{
headerRow[i] = table.Columns[i].ColumnName;
}
table.Rows.InsertAt(headerRow, 0);
}
}
return table;
}
The above almost works, but an exception is thrown when I try and write a column name (obviously a string) into a non-string column of the datatable.
Any ideas for an easy way to achieve this?
Of course the code may give error, because as you told you are assigning none compatible datatypes into one column with specific datatype, columns at Datatable accepts specific datatypes now if you try to change the column datatype to object by creating a copy of table(cloning it) I think the problem will fix:
public static DataTable getTable(String sql, bool includeHeaderRow)
{
DataTable table = new DataTable();
using (SqlDataAdapter adpt = new SqlDataAdapter(sql, getConn()))
{
adpt.Fill(table);
if (includeHeaderRow)
{
DataTable dt = table.Clone();
for (int i = 0; i < table.Columns.Count; i++)
{
dt.Columns[i].DataType = typeof(Object);
}
foreach (DataRow row in table.Rows)
{
dt.ImportRow(row);
}
DataRow headerRow = dt.NewRow();
for (int i = 0; i < table.Columns.Count; i++)
{
headerRow[i] = table.Columns[i].ColumnName;
}
dt.Rows.InsertAt(headerRow, 0);
}
}
return dt;
}

Categories