I'm working with entity framework and right now I'm saving two assignments and want to show them to my gridview.
Here I'm saving them to my database table and show them in the gridview:
The code here:
protected void ButtonAddAssignmentClick(object sender, EventArgs e)
{
Session.Remove("DataTable");
//Add to DB and show in gridview
using (var db = new KnowItCvdbEntities())
{
SPWeb theSite = SPControl.GetContextWeb(Context);
SPUser theUser = theSite.CurrentUser;
string strUserName = theUser.LoginName;
var theEmplAssignment = (
from p
in db.EMPLOYEES
where p.username == strUserName
select p).FirstOrDefault();
_emp = theEmplAssignment;
if (_emp != null)
{
//Create assignment
var myAssignment = new EMPLOYEES_ASSIGNMENT
{
assignment_id = new Random().Next(),
employee_id = _emp.employee_id,
reference_name = TextBoxReference.Text,
company_name = TextBoxCompanyName.Text,
sector = TextBoxSector.Text,
area = TextBoxArea.Text,
from_date = TextBoxFromDate.Text,
to_date = TextBoxToDate.Text,
description = TextBoxDesc.Text,
};
//Create assignment tools
for (int i = 0; i < ListBoxAssignmentTools.Items.Count; i++)
{
var myTool = new ASSIGNMENT_TOOLS
{
assignment_tools_id = new Random().Next(),
assignment_id = myAssignment.assignment_id,
employee_id = myAssignment.employee_id,
tool_name = ListBoxAssignmentTools.Items[i].ToString()
};
myAssignment.ASSIGNMENT_TOOLS.Add(myTool);
}
//Create assignment technology
for (int i = 0; i < ListBoxAssignmentTechnology.Items.Count; i++)
{
var myTech = new ASSIGNMENT_TECHNOLOGY
{
assignment_technology_id = new Random().Next(),
assignment_id = myAssignment.assignment_id,
employee_id = myAssignment.employee_id,
technology_name = ListBoxAssignmentTechnology.Items[i].ToString()
};
myAssignment.ASSIGNMENT_TECHNOLOGY.Add(myTech);
}
//Add assignment to db
_emp.EMPLOYEES_ASSIGNMENT.Add(myAssignment);
db.SaveChanges();
//Populate gridview
var dt = new DataTable();
if (Session["DataTable"] != null)
{
dt = (DataTable)Session["DataTable"];
}
else
{
dt.Columns.Add("Company name");
dt.Columns.Add("Sector");
dt.Columns.Add("Area");
dt.Columns.Add("From");
dt.Columns.Add("To");
dt.Columns.Add("Tools");
dt.Columns.Add("Technology");
dt.Columns.Add("Description");
dt.Columns.Add("Reference");
dt.Rows.Clear();
}
DataRow dr = dt.NewRow();
dr["Company name"] = TextBoxCompanyName.Text;
dr["Sector"] = TextBoxSector.Text;
dr["Area"] = TextBoxArea.Text;
dr["From"] = TextBoxFromDate.Text;
dr["To"] = TextBoxToDate.Text;
dr["Description"] = TextBoxDesc.Text;
dr["Reference"] = TextBoxReference.Text;
string sToolsValue = string.Empty;
for (int i = 0; i < ListBoxAssignmentTools.Items.Count; i++)
{
sToolsValue += ListBoxAssignmentTools.Items[i] + " ";
}
dr["Tools"] = sToolsValue;
string sTechValue = string.Empty;
for (int i = 0; i < ListBoxAssignmentTechnology.Items.Count; i++)
{
sTechValue += ListBoxAssignmentTechnology.Items[i] + " ";
}
dr["Technology"] = sTechValue;
dt.Rows.Add(dr);
Session["DataTable"] = dt;
//Add to gridview
GridViewShowAssignments.DataSource = dt;
GridViewShowAssignments.DataBind();
TextBoxCompanyName.Text = string.Empty;
TextBoxArea.Text = string.Empty;
TextBoxSector.Text = string.Empty;
TextBoxFromDate.Text = string.Empty;
TextBoxToDate.Text = string.Empty;
TextBoxDesc.Text = string.Empty;
TextBoxReference.Text = string.Empty;
ListBoxAssignmentTools.Items.Clear();
ListBoxAssignmentTechnology.Items.Clear();
}
}
}
And I'm using a method on page load that retrieves all assignments on the current logged in user and showing it on the gridview.
But the gridview is populating duplicates! I suspect that I must clear my session on page load but I don't really know how to do it.
The method code:
//Get assignment from db and populate gridview
private void GetEmployeeAssignment(EMPLOYEE theEmpl)
{
Session.Remove("DataTable");
using (var db = new KnowItCvdbEntities())
{
if (_emp != null)
{
var assignmentList = from p in db.EMPLOYEES_ASSIGNMENT.AsEnumerable()
join at in db.ASSIGNMENT_TOOLS.AsEnumerable() on p.assignment_id equals at.assignment_id
join ate in db.ASSIGNMENT_TECHNOLOGY.AsEnumerable() on p.assignment_id equals ate.assignment_id
where p.employee_id == theEmpl.employee_id
select new EmployeeAssignmentInfo
{
CompanyName = p.company_name,
AssignmentId = p.assignment_id,
Area = p.area,
From = p.from_date,
To = p.to_date,
Description = p.description,
Sector = p.sector,
Reference = p.reference_name,
ToolName = at.tool_name,
AssignmentToolsId = at.assignment_tools_id,
TechnologyName = ate.technology_name,
AssignmentTechnologyId = ate.assignment_technology_id
};
foreach (var vAssignment in assignmentList)
{
//Populate gridview
var dt = new DataTable();
if (Session["DataTable"] != null)
{
dt = (DataTable)Session["DataTable"];
}
else
{
dt.Columns.Add("Company name");
dt.Columns.Add("Sector");
dt.Columns.Add("Area");
dt.Columns.Add("From");
dt.Columns.Add("To");
dt.Columns.Add("Tools");
dt.Columns.Add("Technology");
dt.Columns.Add("Description");
dt.Columns.Add("Reference");
dt.Rows.Clear();
}
DataRow dr = dt.NewRow();
dr["Company name"] = vAssignment.CompanyName;
dr["Sector"] = vAssignment.Sector;
dr["Area"] = vAssignment.Area;
dr["From"] = vAssignment.From;
dr["To"] = vAssignment.To;
dr["Description"] = vAssignment.Description;
dr["Reference"] = vAssignment.Reference;
dr["Tools"] = vAssignment.ToolName + " ";
dr["Technology"] = vAssignment.TechnologyName + " ";
dt.Rows.Add(dr);
Session["DataTable"] = dt;
GridViewShowAssignments.DataSource = dt;
GridViewShowAssignments.DataBind();
}
}
else
{
LabelPleaseRegister.Visible = true;
LabelPleaseRegister.Text = "Please register your personal information";
PanelRegisterCv.Visible = false;
PanelRegisterPersonalInfo.Visible = false;
}
}
}
Page load:
protected void Page_Load(object sender, EventArgs e)
{
SPWeb theSite = SPControl.GetContextWeb(Context);
SPUser theUser = theSite.CurrentUser;
string strUserName = theUser.LoginName;
LabelUsername.Text = strUserName;
if (!IsPostBack)
{
_emp = GetEmployee(strUserName);
GetEmployeeAssignment(_emp);
}
}
Just do
Session["DataTable"] = null;
or
Session.Remove("DataTable")
Update your code like:
//Get assignment from db and populate gridview
private void GetEmployeeAssignment(EMPLOYEE theEmpl)
{
Session["DataTable"]=null;
using (var db = new KnowItCvdbEntities())
{
if (_emp != null)
{
var assignmentList = from p in db.EMPLOYEES_ASSIGNMENT.AsEnumerable()
join at in db.ASSIGNMENT_TOOLS.AsEnumerable() on p.assignment_id equals at.assignment_id
join ate in db.ASSIGNMENT_TECHNOLOGY.AsEnumerable() on p.assignment_id equals ate.assignment_id
where p.employee_id == theEmpl.employee_id
select new EmployeeAssignmentInfo
{
CompanyName = p.company_name,
AssignmentId = p.assignment_id,
Area = p.area,
From = p.from_date,
To = p.to_date,
Description = p.description,
Sector = p.sector,
Reference = p.reference_name,
ToolName = at.tool_name,
AssignmentToolsId = at.assignment_tools_id,
TechnologyName = ate.technology_name,
AssignmentTechnologyId = ate.assignment_technology_id
};
var dt = new DataTable();
foreach (var vAssignment in assignmentList)
{
//Populate gridview
if (Session["DataTable"] != null)
{
dt = (DataTable)Session["DataTable"];
}
else
{
dt.Columns.Add("Company name");
dt.Columns.Add("Sector");
dt.Columns.Add("Area");
dt.Columns.Add("From");
dt.Columns.Add("To");
dt.Columns.Add("Tools");
dt.Columns.Add("Technology");
dt.Columns.Add("Description");
dt.Columns.Add("Reference");
dt.Rows.Clear();
}
DataRow dr = dt.NewRow();
dr["Company name"] = vAssignment.CompanyName;
dr["Sector"] = vAssignment.Sector;
dr["Area"] = vAssignment.Area;
dr["From"] = vAssignment.From;
dr["To"] = vAssignment.To;
dr["Description"] = vAssignment.Description;
dr["Reference"] = vAssignment.Reference;
dr["Tools"] = vAssignment.ToolName + " ";
dr["Technology"] = vAssignment.TechnologyName + " ";
dt.Rows.Add(dr);
}
Session["DataTable"] = dt;
GridViewShowAssignments.DataSource = dt;
GridViewShowAssignments.DataBind();
}
else
{
LabelPleaseRegister.Visible = true;
LabelPleaseRegister.Text = "Please register your personal information";
PanelRegisterCv.Visible = false;
PanelRegisterPersonalInfo.Visible = false;
}
}
}
Best Regards
Related
How to convert select new LINQ to DataTable
I need to compare several files using Windows Application form C#.
I have use LINQ and Lambda expression to sum up the duplicates
Please help thanks
I had seen Convert select new to DataTable?. and tried
var firstRecord = records.First();
if (firstRecord == null)
return;
var infos = firstRecord.GetType().GetProperties();
DataTable table = new DataTable();
foreach (var info in infos) {
DataColumn column = new DataColumn(info.Name, info.PropertyType);
table.Columns.Add(column);
}
foreach (var record in records) {
DataRow row = table.NewRow();
for (int i = 0; i < table.Columns.Count; i++)
row[i] = infos[i].GetValue(record);
table.Rows.Add(row);
}
But it had errors for sequence contains no elements.
These are my full codes.
namespace Comparison2._0
{
public partial class ComparisonForm : Form
{
public class FlatFile
{
public string Location { get; set; }
public string Item_Type { get; set; }
public string Type { get; set; }
public double Amount { get; set; }
}
public ComparisonForm()
{
InitializeComponent();
}
private void UploadTransactionReportButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
String path = dialog.FileName;
//String fileName = path.Substring(path.LastIndexOf("\\") + 1);
TransactionFileNameTextBox.Text = path;
}
}
private void UploadMovementReportButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
String path = dialog.FileName;
//String fileName = path.Substring(path.LastIndexOf("\\") + 1);
MovementReportTextBox.Text = path;
}
}
private void UploadFlatfileReportButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
String[] path = dialog.FileNames;
//String fileName = path.Substring(path.LastIndexOf("\\") + 1);
for (int i = 0; i < path.Count(); i++)
FlatfileTextBox.Text += path[i] + "#";
}
}
private void UploadAdjustmentReportButton_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Multiselect = false;
if (dialog.ShowDialog() == DialogResult.OK)
{
String path = dialog.FileName;
AdjustmentReportTextBox.Text = path;
}
}
private void CompareButton_Click(object sender, EventArgs e)
{
OleDbConnection objConn, objConn1, objConn2;
DataTable dt, dt1, dt2, TableA, TableB, TableC;
string sql, sql1, sql2;
OleDbDataAdapter oleDA;
DataSet ds;
string transactionReport = TransactionFileNameTextBox.Text;
string movementReport = MovementReportTextBox.Text;
string adjustmentReport = AdjustmentReportTextBox.Text;
String sConnectionString1 = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" +
transactionReport + ";" + "Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
String sConnectionString2 = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source="
+ movementReport + ";" + "Extended Properties =\"Excel 12.0;HDR=YES;IMEX=1\"";
String sConnectionString3 = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source="
+ adjustmentReport + ";" + "Extended Properties =\"Excel 12.0;HDR=YES;IMEX=1\"";
//TRANSACTION FILE
objConn = new OleDbConnection(sConnectionString1);
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sql = "SELECT * from [Sheet$]";
oleDA = new OleDbDataAdapter(sql, sConnectionString1);
ds = new DataSet();
oleDA.Fill(ds);
TableA = ds.Tables[0];
objConn.Close();
//dataGridView.DataSource = _DtTable;
//MOVEMENT FILE
objConn1 = new OleDbConnection(sConnectionString2);
objConn1.Open();
dt1 = objConn1.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sql1 = "SELECT * from [Sheet$]";
oleDA = new OleDbDataAdapter(sql1, sConnectionString2);
ds = new DataSet();
oleDA.Fill(ds);
TableB = ds.Tables[0];
objConn1.Close();
//dataGridView.DataSource = _DtTable1;
//ADJUSTMENT FILE
objConn2 = new OleDbConnection(sConnectionString3);
objConn2.Open();
dt2 = objConn2.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
sql2 = "SELECT * from [Sheet$]";
oleDA = new OleDbDataAdapter(sql2, sConnectionString3);
ds = new DataSet();
oleDA.Fill(ds);
TableC = ds.Tables[0];
objConn2.Close();
//dataGridView1.DataSource = TableC;
//FLATFILES
//List<string> fileLines = System.IO.File.ReadAllLines(FlatfileTextBox.Text).ToList();
DataTable TableD = ConvertToDataTable(FlatfileTextBox.Text, 4);
//dataGridView1.DataSource = tableD;
DataTable FlatFileTable = new DataTable();
FlatFileTable.Columns.Add(new DataColumn("Location"));
FlatFileTable.Columns.Add(new DataColumn("Item Type"));
FlatFileTable.Columns.Add(new DataColumn("Type"));
FlatFileTable.Columns.Add(new DataColumn("PO Total Cost(Qty Received)"));
FlatFileTable.Columns.Add(new DataColumn("Amount", typeof(double)));
FlatFileTable.Columns.Add(new DataColumn("Amount Difference"));
foreach (DataRow rowA in TableA.Rows)
{
foreach (DataRow rowD in TableD.Rows)
{
if (Convert.ToDouble(rowD["Amount"]) > 0)
{
if (rowA["Location"].ToString().Substring(0, 5).Trim() == rowD["Location"].ToString() && rowD["Type"].ToString() == "GRN" && rowA["Item Type"].ToString() == rowD["Item Type"].ToString())
{
var newRow = FlatFileTable.NewRow();
newRow["Location"] = rowD["Location"];
newRow["Item Type"] = rowD["Item Type"];
newRow["Type"] = rowD["Type"];
newRow["PO Total Cost(Qty Received)"] = rowA["PO Total Cost(Qty Received)"];
//sum += Convert.ToDouble(rowD["Amount"]);
newRow["Amount"] = rowD["Amount"];
var newSort = from row in FlatFileTable.AsEnumerable()
group row by new { Location = row.Field<string>("Location"), Item_Type = row.Field<string>("Item Type"), Type = row.Field<string>("Type") } into grp
select new
{
Location = grp.Key.Location,
//Item_Type = grp.Key.Item_Type,
Type = grp.Key.Type,
Amount = grp.Sum(r => r.Field<double>("Amount"))
};
//dataGridView1.DataSource = table;
//newRow["Amount Difference"] = Convert.ToDouble(rowA["PO Total Cost(Qty Received)"]) - Convert.ToDouble(rowD["Amount"]);
FlatFileTable.Rows.Add(newRow);
//FlatFileTable.Rows.Add(newSort.ToList());
//dataGridView1.DataSource = FlatFileTable;
//DataTable TableZ = newSort.Copt
dataGridView.DataSource = Comparison(TableA, TableB, FlatFileTable);
}
}
}
}
//dataGridView1.DataSource = FlatFileTable;
//dataGridView.DataSource = Comparison(TableA, TableB, newSort.);
//I want to pass into this function so I can compare between them
}
public DataTable ConvertToDataTable(string filePath, int numberOfColumns)
{
DataTable tbl = new DataTable();
tbl.Columns.Add(new DataColumn("Type"));
tbl.Columns.Add(new DataColumn("Amount", typeof(double)));
tbl.Columns.Add(new DataColumn("Location"));
tbl.Columns.Add(new DataColumn("Item Type"));
//foreach(var file in filePath)
string[] MultipleFiles = filePath.Split('#');
for (int i = 0; i < MultipleFiles.Count() - 1; i++)
{
string[] lines = System.IO.File.ReadAllLines(MultipleFiles[i]);
foreach (string line in lines)
{
var cols = line.Split('|');
var count = 0;
DataRow dr = tbl.NewRow();
for (int cIndex = 7; cIndex < 11; cIndex++)
{
dr[count] = cols[cIndex];
count++;
}
tbl.Rows.Add(dr);
}
}
return tbl;
}
public DataTable Comparison(DataTable A, DataTable B, DataTable C)
{
var tableC = new DataTable();
tableC.Columns.Add(new DataColumn("Location"));
tableC.Columns.Add(new DataColumn("Item Type"));
tableC.Columns.Add(new DataColumn("PO Total Cost(Qty Received)"));
tableC.Columns.Add(new DataColumn("Qty Received Actual Cost"));
tableC.Columns.Add(new DataColumn("Amount from FlatFile"));
tableC.Columns.Add(new DataColumn("Amount (Transaction - Movement)"));
tableC.Columns.Add(new DataColumn("Amount (Transaction - FlatFile)"));
foreach (DataRow rowA in A.Rows)
{
foreach (DataRow rowB in B.Rows)
{
foreach (DataRow rowC in C.Rows)
{
if (rowA["Location"].ToString() == rowB["Location"].ToString() && rowA["Item Type"].ToString() == rowB["Item Type"].ToString() &&
rowA["Location"].ToString().Substring(0, 5).Trim() == rowC["Location"].ToString() && rowA["Item Type"].ToString() == rowC["Item Type"].ToString())
{
var newRow = tableC.NewRow();
newRow["Location"] = rowA["Location"];
newRow["Item Type"] = rowA["Item Type"];
newRow["PO Total Cost(Qty Received)"] = rowA["PO Total Cost(Qty Received)"];
newRow["Qty Received Actual Cost"] = rowB["Qty Received Actual Cost"];
newRow["Amount from FlatFile"] = rowC["Amount"];
newRow["Amount (Transaction - Movement)"] = Convert.ToDouble(rowA["PO Total Cost(Qty Received)"]) - Convert.ToDouble(rowB["Qty Received Actual Cost"]);
newRow["Amount (Transaction - FlatFile)"] = Convert.ToDouble(rowA["PO Total Cost(Qty Received)"]) - Convert.ToDouble(rowC["Amount"]);
tableC.Rows.Add(newRow);
}
//}
}
}
}
return tableC;
}
private void ComparisonForm_Load(object sender, EventArgs e)
{
}
}
}
But it had errors for sequence contains no elements.
You are getting the above error because there is no record in the collection apparently and First fails in that case. You need FirstOrDefault which will return null if there is no items in the collection:
var firstRecord = records.FirstOrDefault();
I have two DataGridview's, dgvProducts and dgvCart.
When I transfer a product to from dgvProducts to dgvCart, the specified quantity will deduct from the first datagridview.
But the problem is my textbox search code, it is using a query so the datagridview quantity are reset everytime even when the transaction is not finish.
This is the code for the search of textbox.
private void textOrderSearch_TextChanged(object sender, EventArgs e)
{
if (textOrderSearch.Text != "")
{
crud.FillDataGrid("Select ProductID,BrandName,GenericName,Form,Dosage,Quantity,SellingPrice,D,VE from Products where Status = 'Active' and Quantity > 0 and (ProductID Like '%" + textOrderSearch.Text + "%' or BrandName Like '%" + textOrderSearch.Text + "%' or GenericName Like '%" + textOrderSearch.Text + "%' or Form Like '%" + textOrderSearch.Text + "%' or Dosage Like '%" + textOrderSearch.Text + "%' ) ", ref dgvPOSproduct);
dgvPOSproduct.Columns[0].HeaderText = "ProductID";
dgvPOSproduct.Columns[1].HeaderText = "Brand";
dgvPOSproduct.Columns[2].HeaderText = "Generic";
dgvPOSproduct.Columns[3].HeaderText = "Form";
dgvPOSproduct.Columns[4].HeaderText = "Dosage";
dgvPOSproduct.Columns[5].HeaderText = "Qty";
dgvPOSproduct.Columns[6].HeaderText = "Price";
dgvPOSproduct.Columns[7].HeaderText = "D";
dgvPOSproduct.Columns[8].HeaderText = "VE";
dgvPOSproduct.Columns[0].Width = 65;
dgvPOSproduct.Columns[1].Width = 80;
dgvPOSproduct.Columns[2].Width = 80;
dgvPOSproduct.Columns[3].Width = 58;
dgvPOSproduct.Columns[4].Width = 58;
dgvPOSproduct.Columns[5].Width = 45;
dgvPOSproduct.Columns[6].Width = 55;
dgvPOSproduct.Columns[7].Width = 35;
dgvPOSproduct.Columns[8].Width = 35;
}
else
{
dgvProductSettings();
}
}
And the code for the method of populating the datagridview.
private void dgvProductSettings()
{
crud.FillDataGrid("Select ProductID,BrandName,GenericName,Form,Dosage,Quantity,SellingPrice,D,VE from Products where Status = 'Active' and Quantity > 0", ref dgvPOSproduct);
dgvPOSproduct.Columns[0].HeaderText = "ProductID";
dgvPOSproduct.Columns[1].HeaderText = "Brand";
dgvPOSproduct.Columns[2].HeaderText = "Generic";
dgvPOSproduct.Columns[3].HeaderText = "Form";
dgvPOSproduct.Columns[4].HeaderText = "Dosage";
dgvPOSproduct.Columns[5].HeaderText = "Qty";
dgvPOSproduct.Columns[6].HeaderText = "Price";
dgvPOSproduct.Columns[7].HeaderText = "D";
dgvPOSproduct.Columns[8].HeaderText = "VE";
dgvPOSproduct.Columns[0].Width = 65;
dgvPOSproduct.Columns[1].Width = 80;
dgvPOSproduct.Columns[2].Width = 80;
dgvPOSproduct.Columns[3].Width = 58;
dgvPOSproduct.Columns[4].Width = 58;
dgvPOSproduct.Columns[5].Width = 45;
dgvPOSproduct.Columns[6].Width = 55;
dgvPOSproduct.Columns[7].Width = 35;
dgvPOSproduct.Columns[8].Width = 35;
}
Is there a way to search the datagridview only so it will not need to do a query that is reseting the quantity everytime i do a search? Thank you.
EDIT: added crud method
public crud()
{
cnString = "Data Source=BENJOPC\\SQLEXPRESS;Initial Catalog=MARISCHELLdatabase;Integrated Security=True";
cn = new SqlConnection(cnString);
}
public void FillDataGrid(string sql, ref ns1.BunifuCustomDataGrid dg)
{
try
{
DataSet ds = new DataSet();
cn.Open();
cmd = new SqlCommand(sql, cn);
adptr = new SqlDataAdapter(cmd);
adptr.Fill(ds);
dg.DataSource = "";
dg.DataSource = ds.Tables[0];
}
catch (Exception e)
{
MessageBox.Show("" + e.Message);
}
cn.Close();
}
Yes, there is. You can loop through the rows and set unwanted:
Me.dgwList.Rows(0).Visible = False
However, I would strongly advice to avoid it.
A better way would be to storing your dataset into a Datatable1 like:
' define those as *global* variables (outside subs and functions)
Dim dtMyTable1 as New Datatable
Dim dtMyTable2 as New Datatable
' Load your data from database into first dtMyTable and assign it to DGW
' instead of datasource
dtMyTable1 = ds.tables(0)
Me.dgwList.datasource = dtMyTable1
If you needed to update a list of second DGW every time user clicked a list, then you'd manipulate data into DataTable2 like:
Private Sub UpdateSelection()
For ir = 0 to me.dtMyTable.Rows.Count - 1
Dim dr as datagridviewRow = me.dtMyTable.Rows(ir)
If dr("Brand") = BrandString Then
dtMyTable2.ImportRow(dtMyTable.Item(I).Row)
End If
Next ir
End Sub
But to make a list to add up every next selected value, call this function:
Private Sub AddSelectedRowToSelection()
If Me.dgwList.SelectedRows.Count > 0 Then ' only if a row is selected
' add this row
dtMyTable2.ImportRow(dtMyTable.Item(Me.dgwList.SelectedRows(0).Index).Row)
End If
End Sub
And then put the second db into second DataGridView as datasource:
Me.SeconddgwList.datasource = dtMyTable2
You can empty the second list (delete rows but keep columns) like this:
dtMyTable2.Clear()
EDIT 2: Ahh, I see you're using it for collecting the rows from the first DataGridView. Then it's even simpler, do as above, but always set first table as datasource for the first datagridview and second table as source for second DataGridView. And do not remove old rows, keep them in the second set.
EDIT: Sorry, C# should be like this:
this.dgwList.Rows(0).Visible == false
Datatable dtMyTable = new Datatable();
Datatable dtMyTable2 = new Datatable();
dtMyTable = ds.tables(0);
for (ir = 0; ir <= this.dtMyTable.Rows.Count - 1; ir++) {
datagridviewRow dr = this.dtMyTable.Rows(ir);
if (dr("Brand") == BrandString) {
dtMyTable2.ImportRow(dtMyTable.Item(I).Row);
}
}
private void AddSelectedRowToSelection()
{
// only if a row is selected
if (this.dgwList.SelectedRows.Count > 0) {
// add this row
dtMyTable2.ImportRow(dtMyTable.Item(this.dgwList.SelectedRows(0).Index).Row);
}
}
this.dgwList.datasource = dtMyTable2;
I manage to solve my problem here is the code i used.
DataTable dt = new DataTable("Products");
private void dgvProductNew()
{
try
{
using (SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings["cnn"].ConnectionString))
{
if (cnn.State == ConnectionState.Closed)
cnn.Open();
using (SqlDataAdapter da = new SqlDataAdapter("Select ProductID, BrandName, GenericName, Form, Dosage, Quantity, SellingPrice, D, VE from Products where Status = 'Active' and Quantity > 0", cnn))
{
da.Fill(dt);
dgvPOSproduct.DataSource = dt;
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
and
private void textOrderSearch_TextChanged(object sender, EventArgs e)
{
DataView dv = dt.DefaultView;
dv.RowFilter = string.Format("BrandName like '%{0}%' ", textOrderSearch.Text);
dgvPOSproduct.DataSource = dt;
dgvPOSproduct.Columns[0].HeaderText = "ProductID";
dgvPOSproduct.Columns[1].HeaderText = "Brand";
dgvPOSproduct.Columns[2].HeaderText = "Generic";
dgvPOSproduct.Columns[3].HeaderText = "Form";
dgvPOSproduct.Columns[4].HeaderText = "Dosage";
dgvPOSproduct.Columns[5].HeaderText = "Qty";
dgvPOSproduct.Columns[6].HeaderText = "Price";
dgvPOSproduct.Columns[7].HeaderText = "D";
dgvPOSproduct.Columns[8].HeaderText = "VE";
dgvPOSproduct.Columns[0].Width = 65;
dgvPOSproduct.Columns[1].Width = 80;
dgvPOSproduct.Columns[2].Width = 80;
dgvPOSproduct.Columns[3].Width = 58;
dgvPOSproduct.Columns[4].Width = 58;
dgvPOSproduct.Columns[5].Width = 45;
dgvPOSproduct.Columns[6].Width = 55;
dgvPOSproduct.Columns[7].Width = 35;
dgvPOSproduct.Columns[8].Width = 35;
}
private void txtSearch_TextChanged(object sender, EventArgs e)
{
if (txtSearch.Text != string.Empty)
{
foreach (DataGridViewRow row in gvProducts.Rows)//gvProducts is demo Grid
{
string text = "";
foreach (DataGridViewCell cell in row.Cells)
{
if ((cell.ColumnIndex != 0 && cell.ColumnIndex != 1))
{
text += cell.Value.ToString();
}
}
if (text.ToUpper().Contains(txtSearch.Text.ToUpper()))
{//to Uppper is not compulsory but its for case insensitivity
CurrencyManager currencyManager1 = (CurrencyManager)BindingContext[gvProducts.DataSource];
currencyManager1.SuspendBinding();
row.Visible = true;
currencyManager1.ResumeBinding();
}
else
{
CurrencyManager currencyManager1 = (CurrencyManager)BindingContext[gvProducts.DataSource];
currencyManager1.SuspendBinding();
row.Visible = false;
currencyManager1.ResumeBinding();
}
}
}
else
{
foreach (DataGridViewRow row in gvProducts.Rows)
{
CurrencyManager currencyManager1 = (CurrencyManager)BindingContext[gvProducts.DataSource];
currencyManager1.SuspendBinding();
row.Visible = true;
currencyManager1.ResumeBinding();
}
}
}
I want to export a file by calling a stored procedures from aspx and I want to save the data to a .txt file. Each column must have specific column length that need to be set. Below is my code, but when I run the program, the output only display column name... and no data appears. It look like program not read the row statement. Please help me
protected void Page_Load(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
string str = "Server=KABS;Database=HOT;uid=sa;pwd=DDD;Connection Timeout=6000";
if (Request.QueryString["ProcessName"] != null)
{
using (SqlConnection con = new SqlConnection(str))
{
if (Request.QueryString["ProcessName"].ToString().Equals("Ebill"))
{
using (SqlCommand cmd = new SqlCommand("AR_Ebill_claim", con))
{
cmd.CommandType = CommandType.StoredProcedure;
string compcode = null;
DateTime dateFrom = DateTime.Now;
DateTime dateTo = DateTime.Now;
string episType = null;
string debtorCode = null;
if (Request.QueryString["compcode"] != null)
{
if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["compcode"])))
{
compcode = null;
}
else
{
compcode = Convert.ToString(Request.QueryString["compcode"]);
}
}
if (Request.QueryString["dateFrom"] != null)
{
DateTime dtFrom = DateTime.Parse(Request.QueryString["dateFrom"]);
dtFrom.ToString("dd-MMM-yyyy");
if (dtFrom == null)
{
dateFrom = DateTime.Now;
}
else
{
dateFrom = dtFrom;
}
}
if (Request.QueryString["dateTo"] != null)
{
DateTime dtTo = DateTime.Parse(Request.QueryString["dateTo"]);
dtTo.ToString("dd-MMM-yyyy");
if (dtTo == null)
{
dateTo = DateTime.Now;
}
else
{
dateTo = dtTo;
}
}
if (Request.QueryString["episType"] != null)
{
if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["episType"])))
{
episType = null;
}
else
{
episType = Convert.ToString(Request.QueryString["episType"]);
}
}
if (Request.QueryString["debtorCode"] != null)
{
if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["debtorCode"])))
{
debtorCode = null;
}
else
{
debtorCode = Convert.ToString(Request.QueryString["debtorCode"]);
}
}
cmd.Parameters.Add("#compcode", SqlDbType.VarChar, 100);
cmd.Parameters["#compcode"].Value = compcode;
cmd.Parameters.Add("#dateFrom", SqlDbType.SmallDateTime);
cmd.Parameters["#dateFrom"].Value = dateFrom;
cmd.Parameters.Add("#dateTo", SqlDbType.SmallDateTime);
cmd.Parameters["#dateTo"].Value = dateTo;
cmd.Parameters.Add("#episType", SqlDbType.VarChar, 40);
cmd.Parameters["#episType"].Value = episType;
cmd.Parameters.Add("#debtorCode", SqlDbType.VarChar, 100);
cmd.Parameters["#debtorCode"].Value = debtorCode;
con.Open();
//cmd.ExecuteNonQuery();
//gdBill.EmptyDataText = "No Records Found";
//gdBill.DataSource = cmd.ExecuteReader();
//gdBill.DataBind();
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = cmd;
da.Fill(dt);
string txt = string.Empty;
if (dt.Columns.Count > 0)
{
foreach (DataColumn column in dt.Columns)
{
//Add the Header row for Text file.
txt += column.ColumnName + "\t\t";
}
}
//Add new line.
txt += "\r\n";
if (dt.Rows.Count > 0)
{
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
//Add the Data rows.
txt += row[column.ColumnName].ToString() + "\t\t";
}
//Add new line.
txt += "\r\n";
}
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=E-Billing.txt");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(txt);
Response.Flush();
Response.End();
Cursor.Current = Cursors.AppStarting;
}
}
//cmd.Dispose();
con.Close();
}
}
}
I tested your code and it works like it should. The problem is that the stored procedure AR_Ebill_claim returns zero rows. But there are no errors so the column names do get exported.
I think the problem lies with the parameters. Check those first and test if the stored procedure gives the results you want in SQL server studio or a similar program.
i already got the solutions as my code below :)
if (Request.QueryString["ProcessName"].ToString().Equals("Ebill"))
{
using (SqlCommand cmd = new SqlCommand("AR_Ebill_claim", con))
{
cmd.CommandType = CommandType.StoredProcedure;
string compcode = null;
DateTime dateFrom = DateTime.Now;
DateTime dateTo = DateTime.Now;
string episType = null;
string debtorCode = null;
if (Request.QueryString["compcode"] != null)
{
if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["compcode"])))
{
compcode = null;
}
else
{
compcode = Convert.ToString(Request.QueryString["compcode"]);
}
}
if (Request.QueryString["dateFrom"] != null)
{
DateTime dtFrom = DateTime.Parse(Request.QueryString["dateFrom"]);
dtFrom.ToString("dd-MMM-yyyy");
if (dtFrom == null)
{
dateFrom = DateTime.Now;
}
else
{
dateFrom = dtFrom;
}
}
if (Request.QueryString["dateTo"] != null)
{
DateTime dtTo = DateTime.Parse(Request.QueryString["dateTo"]);
dtTo.ToString("dd-MMM-yyyy");
if (dtTo == null)
{
dateTo = DateTime.Now;
}
else
{
dateTo = dtTo;
}
}
if (Request.QueryString["episType"] != null)
{
if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["episType"])))
{
episType = null;
}
else
{
episType = Convert.ToString(Request.QueryString["episType"]);
}
}
if (Request.QueryString["debtorCode"] != null)
{
if (string.IsNullOrEmpty(Convert.ToString(Request.QueryString["debtorCode"])))
{
debtorCode = null;
}
else
{
debtorCode = Convert.ToString(Request.QueryString["debtorCode"]);
}
}
cmd.Parameters.Add("#compcode", SqlDbType.VarChar, 100);
cmd.Parameters["#compcode"].Value = compcode;
cmd.Parameters.Add("#dateFrom", SqlDbType.SmallDateTime);
cmd.Parameters["#dateFrom"].Value = dateFrom;
cmd.Parameters.Add("#dateTo", SqlDbType.SmallDateTime);
cmd.Parameters["#dateTo"].Value = dateTo;
cmd.Parameters.Add("#episType", SqlDbType.VarChar, 40);
cmd.Parameters["#episType"].Value = episType;
cmd.Parameters.Add("#debtorCode", SqlDbType.VarChar, 100);
cmd.Parameters["#debtorCode"].Value = debtorCode;
con.Open();
//cmd.ExecuteNonQuery();
//gdBill.EmptyDataText = "No Records Found";
//gdBill.DataSource = cmd.ExecuteReader();
//gdBill.DataBind();
string outputFilePath = Server.MapPath("~/Documents/EClaim.txt");
if (File.Exists("~/Documents/EClaim.txt"))
{
File.Delete("~/Documents/EClaim.txt");
}
SqlDataAdapter da = new SqlDataAdapter();
DataTable dt = new DataTable();
da.SelectCommand = cmd;
da.Fill(dt);
int[] maxLengths = new int[dt.Columns.Count];
for (int i = 0; i < dt.Columns.Count; i++)
{
maxLengths[i] = dt.Columns[i].ColumnName.Length;
foreach (DataRow row in dt.Rows)
{
if (!row.IsNull(i))
{
int length = row[i].ToString().Length;
if (length > maxLengths[i])
{
maxLengths[i] = length;
}
}
}
}
using (StreamWriter sw = new StreamWriter(outputFilePath, false))
{
//for (int i = 0; i < dt.Columns.Count; i++)
//{
// sw.Write(dt.Columns[i].ColumnName.PadRight(maxLengths[i] + 2));
//}
sw.WriteLine();
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
if (!row.IsNull(i))
{
sw.Write(row[i].ToString().PadRight(maxLengths[i] + 1));
}
else
{
sw.Write(new string(' ', maxLengths[i] + 1));
}
}
sw.WriteLine();
}
sw.Close();
}
//string filePath = "~/Documents/EBilling.txt";
//Response.ContentType = "application/text";
//Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filePath + "\"");
//Response.TransmitFile(Server.MapPath(filePath));
////Response.End();
}
I have a DataGridView on WindowsForm where I'm passing data from my database. The purpose of this DataGridView is to enable to user to click on a value and modify it. However, I don't want the user to leave the value blank, add words, only numbers.. and of course not change the Id, which is the primary key of my table.
I'm trying to achieve this by disabling the column which host the id of the table, however I don't know how to tell that column to disable editing.
Here is my code:
public partial class eraseGrade : Form
{
Conexion con;
String rut;
DataTable dt;
SqlDataAdapter sda;
SqlCommandBuilder scb;
public eraseGrade()
{
InitializeComponent();
cbxAsig.Enabled = false;
cbxAsig.Enabled = false;
btnNotas.Enabled = false;
btnBorra.Enabled = false;
}
private void btnBuscar_Click_1(object sender, EventArgs e)
{
Conexion con = Conexion.saberEstado();
rut = txtRut.Text.Trim();
if (validarTXTVacios(txtRut))
{
MessageBox.Show("Add a Rut, please");
}
else
{
Alumno a = new Alumno(rut);
a.buscar(a);
cbxAsig.Items.Clear();
if (a.Nombre != null)
{
lblNombre.Text = a.Nombre + " " + a.Apellido;
cbxAsig.Enabled = true;
AsignaturaAlumno b = new AsignaturaAlumno();
List<AsignaturaAlumno> l = b.buscarTodosByAlumno(rut);
List<String> codigosAsig = new List<string>();
if (l.Count != 0)
{
for (int i = 0; i < l.Count(); i++)
{
codigosAsig.Add(l.ElementAt(i).Cod_asig.ToString());
}
Asignatura asigT = new Asignatura();
List<Asignatura> asig = new List<Asignatura>();
for (int i = 0; i < codigosAsig.Count(); i++)
{
asig.Add(asigT.buscarbyCod(codigosAsig.ElementAt(i).ToString()));
}
for (int i = 0; i < asig.Count(); i++)
{
cbxAsig.Items.Add(asig.ElementAt(i).CodAsignatura);
}
cbxAsig.Enabled = true;
btnNotas.Enabled = true;
}
}
else
{
lblNombre.Text = "";
MessageBox.Show("Alumno no encontrado");
lblAsig.Text = "";
cbxAsig.Enabled = false;
btnNotas.Enabled = false;
btnBorra.Enabled = false;
}
}
}
private void cbxAsig_SelectedIndexChanged(object sender, EventArgs e)
{
Conexion con = Conexion.saberEstado();
Asignatura asignatura = new Asignatura();
Asignatura l = asignatura.buscarbyCod(cbxAsig.SelectedItem.ToString());
lblAsig.Text = l.Nombre + " (" + l.IdSeccion + ")";
}
Here is the code that obtains data from the database and inserts it into the DataGridView.
private void btnNotas_Click(object sender, EventArgs e)
{
Conexion con = Conexion.saberEstado();
if (cbxAsig.SelectedItem != null)
{
String codigo = cbxAsig.SelectedItem.ToString();
sda = new SqlDataAdapter(#"SELECT id, num_eval AS Evaluacion, porcentaje AS Porcentaje, nota AS Nota FROM registro WHERE rut = #rut AND cod_asig = #cod_asig", con.Con);
sda.SelectCommand.Parameters.AddWithValue("#rut", rut);
sda.SelectCommand.Parameters.AddWithValue("#cod_asig", codigo);
dt = new DataTable();
sda.Fill(dt);
dataGridView1.DataSource = dt;
btnBorra.Enabled = true;
}
else
{
MessageBox.Show("Seleccione una asignatura");
}
}
public Boolean validarTXTVacios(TextBox r)
{
if (txtRut.Text.Equals(""))
{
return true;
}
return false;
}
Here is the button that updates the table with the new data from the columns. It doesn't respect primary keys or data types.
private void btnBorra_Click(object sender, EventArgs e)
{
scb = new SqlCommandBuilder(sda);
sda.Update(dt);
}
}
}
Just set that column's ReadOnly to true like this:
dataGridView1.Columns[0].ReadOnly = true;
You should change 0 to the id's column index.
EDIT: To validate a column to be for example int you could do like this:
dataGridView1.Columns[0].ReadOnly = true;
dataGridView1.AllowUserToAddRows = false;
foreach (DataGridViewRow row in dataGridView1.Rows)
{
int x;
if (int.TryParse(row.Cells[1].Value.ToString(), out x))
{
MessageBox.Show("Valid");
}
}
You can achieve this by setting Row.Cells[cellIndex].Enabled = false; during GridView RowDataBound event.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[cellIndex].Enabled = false;
}
}
Alter cellIndex to your actual id cell index.
I am trying to refresh the datatablewith new content after click the button but it again shows the previous values also. I tried clear() but it doesn't work for me
protected void btnListItems_Click(object sender, EventArgs e)
{
lblMessage.Visible = false;
//lblEnddatse.Visible = true;
Boolean status = true;
Util objUtil = new Util();
String Message = "";
DateTime SDate = new DateTime();
DateTime EDate = new DateTime();
string str = "";
DataTable tbl = new DataTable();
DataTable dt = new DataTable();
DataRow dr;
String[] s1;
dt.Clear();
//DirectoryInfo d = new DirectoryInfo();
s1 = Directory.GetFiles(#"C:/TextFiles");
for (int i = 0; i <= s1.Length - 1; i++)
{
if (i == 0)
{
//Add Data Grid Columns with name
dt.Columns.Add("FileName");
dt.Columns.Add("GeneratedTime");
}
//Get each file information
FileInfo f = new FileInfo(s1[i]);
FileSystemInfo f1 = new FileInfo(s1[i]);
dr = dt.NewRow();
//Get File name of each file name
dr["FileName"] = f1.Name;
dr["GeneratedTime"] = f1.CreationTime.Date.ToString("dd/MM/yyyy");
string a = f1.CreationTime.Date.ToString("dd/MM/yyyy");
//Insert collected file details in Datatable
string fromdate = txtFromDate.Text.ToString();
string todate = txtToDate.Text.ToString();
if ((DateTime.ParseExact(a.ToString(),"dd/MM/yyyy",System.Globalization.CultureInfo.InvariantCulture)) >= DateTime.ParseExact(fromdate.ToString(),"dd/MM/yyyy",System.Globalization.CultureInfo.InvariantCulture))
{
if ((DateTime.ParseExact(a.ToString(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture)) <= DateTime.ParseExact(todate.ToString(), "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture))
{
dt.Rows.Add(dr);
}
}
if ((f.Length / 1024) > 5000)
{
lblMessage.Text = "" + f1.Name + " had reach its size limit.";
}
else
{ }
}
if (dt.Rows.Count > 0)
{
gvFileGenStatus.DataSource = dt;
gvFileGenStatus.DataBind();
}
}
How can I refresh the datagridview displayed data every time I click button after I switch the date.
Thanks For the help in advance..
Try:
gvFileGenStatus.Rows.Clear();
dt.Dispose();
or in
DataTable dt_null = new DataTable();
if (dt.Rows.Count > 0)
{
gvFileGenStatus.DataSource = dt_null;
gvFileGenStatus.DataBind();
}