Im having trouble fetching ID of selected value from combobox, cna i get some help? the program should get the id of the selected string in the combobox from database.
private void GetValues_Click(object sender, RoutedEventArgs e)
{
ReportesAsistenciaTableAdapter ada = new ReportesAsistenciaTableAdapter();
DataTable dt = ada.GetDataBy((int)selectClass.SelectedItem, dateBox.Text);
if (dt.Rows.Count > 0)
{
DataTable dtNew = ada.GetDataBy((int)selectClass.SelectedItem, dateBox.Text);
EstudiantesList.ItemsSource = dtNew.ToString();
}
else
{
Estudiantes1TableAdapter studentsAdapter = new Estudiantes1TableAdapter();
DataTable dtStudents = studentsAdapter.GetDataByClaseID((int)selectClass.SelectedItem);
foreach (DataRow row in dtStudents.Rows)
{
ada.InsertQuery((int)row[0], (int)selectClass.SelectedItem, dateBox.Text, "", row[1].ToString(), selectClass.Text) ;
}
DataTable dtNew = ada.GetDataBy((int)selectClass.SelectedItem, dateBox.Text);
EstudiantesList.ItemsSource = dtNew.ToString();
}
Related
i have a question. I have a ComboBoxColumn and want to populate Data from Database via ComboBox Variable inside this Column. How can i achieve this.
This snippet I tried doesnt doesn't work
ComboBoxColumn.Items.AddRange("One", "Two", "Three", "Four");
My problem is i getting Data inside another function that will save all the values inside a ComboBox Variable (that every Functions has Access to) and i want to fill the Cell in DataGridView via Column-/Row-Index like this:
private ComboBox ComboBoxItems
private void datagridview_CellClick(object sender, DataGridViewCellEventArgs e)
{
try
{
int col1 = datagridview.Columns["datagridview_col1"].Index;
int col2 = datagridview.Columns["datagridview_col2"].Index;
int col3 = datagridview.Columns["datagridview_col2"].Index;
if ((e.ColumnIndex == col1))
{
fill_col2();
}
else if ((e.ColumnIndex == col2))
{
datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = ComboBoxItems1;
foreach (var item in ComboBoxItems1.Items)
{
Console.WriteLine(ComboBoxItems1.Items.Count);
Console.WriteLine(item.ToString());
}
if (!String.IsNullOrEmpty(section))
{
fill_col3();
}
}
else if ((e.ColumnIndex == col3))
{
datagridview.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = ComboBoxItems2;
}
}
catch (Exception ex)
{
MessageBox.Show("Error loading Data!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
Has anyone an idea for a good working solution?
If you want to set the ComboboxColumn datasource, you can set it while you define the ComboboxColumn.
var ComboCol= new DataGridViewComboBoxColumn
{
HeaderText = "ComboCol",
Name = "ComboCol",
DataSource = new List<string> {"One", "Two", "Three", "Four"}
};
Then before fill the combobox with the data from database, you need to convert the cell to DataGridViewComboBoxCell first.
DataSet ds;
string connetionString = #"Connection String";
using (SqlConnection conn = new SqlConnection(connetionString))
{
SqlDataAdapter sda = new SqlDataAdapter("Select * From TestTable", conn);
ds = new DataSet();
sda.Fill(ds, "TableName");
}
DataGridViewComboBoxCell ComboCell;
foreach (DataRow row in ds.Tables[0].Rows)
{
int index = dataGridView1.Rows.Add();
dataGridView1.Rows[index].Cells["CommonCol1"].Value = row[0];
ComboCell= (DataGridViewComboBoxCell)(dataGridView1.Rows[index].Cells["ComboCol"]);
ComboCell.Value = row[1].ToString();
}
Hope this can help you.
For example I have a datagridview1 with data imported from a excel file and there are 12 columns: date, Name, Activity, Project,time, comment,ect. and 1000 row.
What I want to do is to filter only all with the Project name in project column.
for example I have support as a (Projectname) I want to show all columns filtyring by support rows.
I have combobox to select which column I need to filter it( e.g Project) here,
I tried with this code but it dose not work.
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string projektItem = comboBox1.Items[comboBox1.SelectedIndex].ToString();
if (projektItem == "Project") {
foreach (DataRow dataRow in dataGridView1.Rows)
{
StringBuilder filter = new StringBuilder();
for (int i = 0; i < dataGridView1.Columns.Count - 1; i++)
{
filter.Append(dataRow[i].ToString());
filter.Append("\t");
}
dataGridView1.DataSource = filter.ToString();
}
if (projektItem == "Name") {
}
if (projektItem == "Aktivity") {
}
}
This is how I do it. convert datagridview to datatable
And this is func for filter purpose:
Hold the origin table to go back if you turn your filter off
//datagrid to datatable
DataTable datatable = new DataTable();
datatable = (DataTable)dataGridView1.DataSource;
//datatableOrigin to hold your origin table
DataTable originTable = null;
// find Function
Public void Find(string column, string st)
{
DataRow[] dtResult;
DataTable holder = New DataTable;
//get datatable Schema
DataTable holder = datatable.Clone();
holder.Rows.Clear();
If (originTable != null)
datatable = originTable;
Else
originTable = datatable;
//select return datarow array
dtResult = datatable.Select("[" + column + "] LIKE '%" + st + "%'");
//import all your result into holder
foreach(DataRow dr In dtResult){holder.ImportRow(dr);}
//pass from holder to datatable
datatable = holder.Copy();
holder.Clear();
}
public void showDT()
{
dataGridView1.DataSource = datatable;
}
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
// choose your column here
}
private void btn_Clicked(object sender, EventArgs e)
{
Find('YourColumn, 'your search string);
showDT();
}
I've got a dropdown whose values are retrieved from a database. I am retrieving ID and name from the database.
public void GetDepartment_temp()
{
try
{
DataTable dt = new DataTable();
listBoxDepartment.ClearSelection();
Get_Department objDAL = new Get_Department();
dt = objDAL.Get_Hospital_Department();
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
listBoxDepartment.Items.Add(new ListItem(row["department_name"].ToString(), row["department_id"].ToString()));
}
}
}
catch (Exception) { }
}
I've got to show the number of employees of each department in the text box. Suppose a user selects human department, then the text box should display the number of employees in that department.
For the ListBox, only two values from the database can be retrieved. How can I show the number of employee in this condition?
public DataTable Get_Hospital_Department()
{
try
{
DataTable dt = new DataTable();
dt = DbAccessHelper.ExecuteDataSet("p_get_hospital_department", true).Tables[0];
return dt;
}
catch (Exception) { return null; }
}
CREATE PROCEDURE [dbo].[p_get_hospital_department]
AS
BEGIN
SET NOCOUNT ON;
SELECT department_id
,department_name
FROM [dbo].[tbl_hospital_department];
END
The statement For the ListBox, only two values from the database can be retrieved. is not correct. You can populate the datatable with as many fields as you want. However, you can set only the Value and text attributes of the Listbox item as you have done.
Change the stored procedure code to fetch the employee count also.
Mark your datatable dt as static and public.
Fetch the datable and you can play with the data as you want. You can fetch the employee count in the textbox on listview selected index changed as shown below:
public static DataTable dt = new DataTable();
public void GetDepartment_temp()
{
try
{
string connString = ConfigurationManager.ConnectionStrings["SOConnectionString"].ConnectionString;
SqlConnection connection = new SqlConnection(connString);
SqlCommand command =
new SqlCommand(
"select Department.DepartmentID, Department.[Department Name], count( Department.DepartmentID) as empCount from Department join Employee on Department.DepartmentID = Employee.DepartmentID group by Department.DepartmentID, Department.[Department Name]",
connection);
command.Connection.Open();
SqlDataAdapter da = new SqlDataAdapter(command);
da.Fill(dt);
dt.PrimaryKey = new DataColumn[] {dt.Columns["DepartmentID"]};
ListBox1.ClearSelection();
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
ListBox1.Items.Add(new ListItem(row["Department Name"].ToString(),
row["DepartmentID"].ToString()));
}
}
}
catch (Exception ex)
{
}
}
protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
DataRow dr = dt.Rows.Find(Convert.ToInt32(ListBox1.SelectedItem.Value));
TextBox5.Text = dr["empCount"].ToString();
}
I have created a class file. In that class file, i have created a method name as getdata of type dataset or datatable. This method is to retrieve/fetch data from database and return dataset or datatable object.
I want to display data from dataset or datatable object using combobox event into textboxes.
private void comboBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
try
{
DataOperation DO = new DataOperation();
//DataSet DS = new DataSet();
// DS = DO.GetCompnyDetails(Convert.ToInt32(CmBxCompanyName.Text),
"SelectById");
//txtCompanyId.Text = DS.Tables[0].Rows[0["c_id"].ToString();
//txt_mno.Text = DS.Tables[0].Rows[0]["cont_no"].ToString();
//txt_add.Text = DS.Tables[0].Rows[0]["address"].ToString();
//txt_vno.Text = DS.Tables[0].Rows[0]["vat_no"].ToString();
//txtCstNo.Text = DS.Tables[0].Rows[0]["CSTNo"].ToString();
//txt_eid.Text = DS.Tables[0].Rows[0]["e_id"].ToString();
}
}
private void comboBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
{
try
{
DataOperation DO = new DataOperation();
DataTable Dt;
Dt = DO.GetPymntDetails(Convert.ToInt32(CmBxCompanyName.Selected Index), "SelectById");
if (Dt != null)
{
txtCompanyId.Text = Dt.Rows[0].ItemArray[0].ToString();
txt_mno.Text = Dt.Rows[0].ItemArray[1].ToString();
txt_add.Text = Dt.Rows[0].ItemArray[2].ToString();
txt_vno.Text = Dt.Rows[0].ItemArray[3].ToString();
txtCstNo.Text = Dt.Rows[0].ItemArray[4].ToString();
txt_eid.Text = Dt.Rows[0].ItemArray[5].ToString();
}
}
}
if (Dt.Rows.Count > 0)
{
txtCompanyId.Text = Dt.Rows[0][0].ToString();
txt_mno.Text = Dt.Rows[0][1].ToString();
txt_add.Text = Dt.Rows[0][2].ToString();
txt_vno.Text = Dt.Rows[0][3].ToString();
txtCstNo.Text = Dt.Rows[0][4].ToString();
txt_eid.Text = Dt.Rows[0][5].ToString();
}
I created a form with two Datagridviews. One of these DataGridViews is filled with data from a Database and it is the source. The second DataGridView should be filled with the selected rows from the source Datagridview after I use a Button.
The first step if fill my DataTable is filled this :
public DataTable loadMatImpTable(String query)
{
myConn.Open();
SQLiteCommand cmd = new SQLiteCommand(query, myConn);
SQLiteDataAdapter sda = new SQLiteDataAdapter();
sda.SelectCommand = cmd;
DataTable dt= new DataTable();
sda.Fill(dt);
return dt;
}
After that I fill my source DataGridView:
DataTable dt = lt.loadMatImpTable(queryMat);
this.matExpDataGridVW.Rows.Clear();
foreach (DataRow item in dt.Rows)
{
int n = matExpDataGridVW.Rows.Add();
matExpDataGridVW.Rows[n].Cells[0].Value = false;
matExpDataGridVW.Rows[n].Cells[1].Value = item["MaterialID"].ToString();
matExpDataGridVW.Rows[n].Cells[2].Value = item["Name"].ToString();
matExpDataGridVW.Rows[n].Cells[3].Value = item["Preis"];
matExpDataGridVW.Rows[n].Cells[4].Value = item["Anzahl"].ToString();
matExpDataGridVW.Rows[n].Cells[5].Value = item["Datum"].ToString();
}
And then I push the "ExportButton" and all Selected Rows are copied to the second DatagRidview. But I don't wont't a copy of the rows in the second DataGridview. I will move the selected rows. So I tried in a remove of the items in a foreach loop:
private void mvImpSelectionBT_Click(object sender, EventArgs e)
{
foreach (DataGridViewRow item in matExpDataGridVW.Rows)
{
if ((bool)item.Cells[0].Value == true)
{
int n = matImpDataGridVW.Rows.Add();
matImpDataGridVW.Rows[n].Cells[0].Value = false;
matImpDataGridVW.Rows[n].Cells[1].Value = item.Cells[1].Value.ToString();
matImpDataGridVW.Rows[n].Cells[2].Value = item.Cells[2].Value.ToString();
matImpDataGridVW.Rows[n].Cells[3].Value = item.Cells[3].Value.ToString();
matImpDataGridVW.Rows[n].Cells[4].Value = item.Cells[4].Value.ToString();
matImpDataGridVW.Rows[n].Cells[5].Value = item.Cells[5].Value.ToString();
}
}
#Delete all Selected rows
foreach (DataGridViewRow item in matExpDataGridVW.SelectedRows)
{
matExpDataGridVW.Rows.Remove(item);
}
}
But if I tried the deletion in this way. All selected rows be copied but only the last selected row be deleted in the source DatGridView. Whats the best way to delete this selected rows?
Create a list of rows while you are copying, and then use that list as a basis for deleting your rows from the source.
private void mvImpSelectionBT_Click(object sender, EventArgs e)
{
List<DataRow> rowsToDelete = new List<DataRow>();
foreach (DataGridViewRow item in matExpDataGridVW.Rows)
{
if ((bool)item.Cells[0].Value == true)
{
//copy row
int n = matImpDataGridVW.Rows.Add();
matImpDataGridVW.Rows[n].Cells[0].Value = false;
matImpDataGridVW.Rows[n].Cells[1].Value = item.Cells[1].Value.ToString();
matImpDataGridVW.Rows[n].Cells[2].Value = item.Cells[2].Value.ToString();
matImpDataGridVW.Rows[n].Cells[3].Value = item.Cells[3].Value.ToString();
matImpDataGridVW.Rows[n].Cells[4].Value = item.Cells[4].Value.ToString();
matImpDataGridVW.Rows[n].Cells[5].Value = item.Cells[5].Value.ToString();
//add to list
rowsToDelete.Add(item);
}
}
foreach(DataRow row in rowsToDelete)
{
matExpDataGridVW.Rows.Remove(row);
}
}
Another way to do this, with only one loop, is to use a loop with an iterator instead of a foreach loop.
for (int i = matExpDataGridVW.Rows.Count - 1; i >= 0; i--)
{
if ((bool)matExpDataGridVW.Rows[i].Cells[0].Value == true)
{
//copy row
int n = matImpDataGridVW.Rows.Add();
matImpDataGridVW.Rows[n].Cells[0].Value = false;
matImpDataGridVW.Rows[n].Cells[1].Value = matExpDataGridVW.Rows[i].Cells[1].Value.ToString();
matImpDataGridVW.Rows[n].Cells[2].Value = matExpDataGridVW.Rows[i].Cells[2].Value.ToString();
matImpDataGridVW.Rows[n].Cells[3].Value = matExpDataGridVW.Rows[i].Cells[3].Value.ToString();
matImpDataGridVW.Rows[n].Cells[4].Value = matExpDataGridVW.Rows[i].Cells[4].Value.ToString();
matImpDataGridVW.Rows[n].Cells[5].Value = matExpDataGridVW.Rows[i].Cells[5].Value.ToString();
//delete row
matExpDataGridVW.Rows[i].Delete();
}
matExpDataGridVW.AcceptChanges();
}
If you want "move"(add to destination and remove from source) selected rows to another DataGridView. Try to move items by using DataSources
Load data to original DataGridView
private DataTable _OriginalData;
private DataTable _SelectedData;
private void LoadData()
{
string yourQuery = "SELECT ... FROM ...";
_OriginalData = loadMatImpTable(yourQuery);
//copy structure of original DataTable to the selected table
_SelectedData = _OriginalData.Clone();
//Fill DataGridView
this.matExpDataGridVW.DataSource = _OriginalData;
this.matImpDataGridVW.DataSource = _SelectedData;
//Columns will be generate automatically
//If you want use predefined columns create them through designer or with code
//And set then DataGridView.AutoGenerateColumns = false;
}
Then export items will be like this
private void ExportSelectedRows()
{
foreach DataRow row in matExpDataGridVW.SelectedRows
.Cast<DataGridViewRow>()
.Select(r => r.DataBoundItem as DataRowView)
.Where(drv => drv != null)
.Select(drv => drv.Row)
{
_SelectedData.ImportRow(row);
_OriginalData.Rows.Remove(row);
}
}