Pass DateTimePicker Value to a stored procedure C# - c#

I have DataGridView and DateTimePicker and I want to show data in DataGridView based on DateTimePicker value.
Here is the stored procedure:
create proc Get_Employers_All_Day
#Date_Day date
as
SELECT
[Employer_ID] as 'رقم الموظف'
, Employer_Name as 'اسم الموظف'
FROM [dbo].[Come_Out]
inner join Employers
on Employers .Epmloyer_ID = Come_Out .Employer_ID
where
Come_Out .Status = '2'
and Come_Out .Data_Come_Out = #Date_Day
Here is the C# code:
public void Get_Employers_All_Day(DateTime Date_Day)
{
DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
DAL.Open();
SqlParameter[] param = new SqlParameter[1];
param[0] = new SqlParameter("#Date_Day", SqlDbType.DateTime);
param[0].Value = Date_Day;
DAL.ExecuteCommand("Get_Employers_All_Day", param);
DAL.Close();
}
and the event :
private void Frm_Daily_Come_Out_Load(object sender, EventArgs e)
{
BL.Employers emp = new BL.Employers();
dataGridView1.DataSource = emp.Get_Employers_All_Day(dateTimePicker1 .Value );
}
The error is:
cannot implicitly convert type 'void' to 'object'

Your Get_Employers_All_Day() method has a return type of void, meaning it has no return type.
Modify it to return the data you need. If your DAL.ExecuteCommand() returns a DataTable, for example, modify it to return that:
public DataTable Get_Employers_All_Day(DateTime Date_Day)
{
...
...
DataTable result;
try
{
result = DAL.ExecuteCommand("Get_Employers_All_Day", param);
}
finally
{
// Even if ExecuteCommand() fails, close any open connections
DAL.Close();
}
return result;
}

Related

Specified cast is not valid when I try to cast to (int?)

I have this code to save data to database
for (int i = 0; i < dt.Rows.Count; i++)
{
var row = dt.Rows[i];
await stock.AddProjectNeedsBoltsTest(Convert.ToInt32(row["Quantité"]),
(int?)row["Filetage"],
Convert.ToInt32(row["idProject"]),
(int?)row["idCategory"],
(int?)row["idType"]).ConfigureAwait(true);
}
and this the code behind AddProjectNeedsBoltsTest
public async Task AddProjectNeedsBoltsTest(int Quantity, int? Filetage, int IdProject, int? IdCategory, int? IdType)
{
DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
await Task.Run(() => DAL.Open()).ConfigureAwait(false);
SqlParameter[] param = new SqlParameter[5];
param[0] = new SqlParameter("#Quantity", SqlDbType.Int)
{
Value = Quantity
};
param[1] = new SqlParameter("#Filetage", SqlDbType.Int)
{
Value = Filetage.HasValue ? Filetage : (object)DBNull.Value
};
param[2] = new SqlParameter("#IdProject", SqlDbType.Int)
{
Value = IdProject
};
param[3] = new SqlParameter("#IdCategory", SqlDbType.Int)
{
Value = IdCategory.HasValue ? IdCategory : (object)DBNull.Value
};
param[4] = new SqlParameter("#IdType", SqlDbType.Int)
{
Value = IdType.HasValue ? IdType : (object)DBNull.Value
};
await Task.Run(() => DAL.ExcuteCommande("AddProjectNeedsBoltsTest", param)).ConfigureAwait(false);
DAL.Close();
}
and this is my stored procedure
CREATE PROCEDURE dbo.AddProjectNeedsBoltsTest
#Quantity int
,#Filetage int
,#IdProject int
,#IdCategory int
,#IdType int
AS
INSERT INTO [dbo].[ProjectNeedsBolts]
([Quantity]
,[Filetage]
,[IdProject]
,[IdCategory]
,[IdType])
VALUES
(#Quantity
,#Filetage
,#IdProject
,#IdCategory
,#IdType)
Now when I click on save button I get this error
An exception of type 'System.InvalidCastException' occurred in Smart Industrial Management.exe but was not handled in user code
Additional information: Specified cast is not valid.
On debugging on this line of code
(int?)row["Filetage"]
I get this error message
Cannot unbox 'row["Filetage"]' as a 'int?'
Update:This is my datatable
DataTable dt = new DataTable();
void CreateDataTable()
{
dt.Columns.Add("Quantité");
dt.Columns.Add("Filetage");
dt.Columns.Add("idProject");
dt.Columns.Add("idCategory");
dt.Columns.Add("idType");
gridControl1.DataSource = dt;
}
If I try with
dt.Columns.Add("Filetage", typeof(int?));
I get error message
DataSet does not support System.Nullable<>
Indeed, DataTable doesn't support int? - you'd add it as an int - with DataTable handing nullability separately. For the cast, there are two possibilities:
the value is DBNull
the value is something else - not an int; perhaps a long or a string
For 1 - just check whether the value is DBNull, and if so: don't try casting it to an int - handle the null yourself.
For 2 - you'd have to do your own parsing / conversion code, but frankly: it would be better to fix the database so that it is right
However, frankly: I am going to say: tools like Dapper make this just go away - no DataTable, no worries. You'd just use things like a List<ProjectNeedsBolts> for POCO:
public class ProjectNeedsBolts {
public int Quantity {get;set;}
public int IdType {get;set;}
}
(or int?, or whatever else you need), then get the library to do all the work for you:
await conn.ExecuteNonQueryAsync(
"AddProjectNeedsBoltsTest",
new { Quantity, Filetage, IdProject, IdCategory, IdType }
commandType: CommandType.StoredProcedure).ConfigureAwait(false);
or:
var data = await conn.QueryAsync<ProjectNeedsBolts>(
"your select sql",
new {...} // parameters
}).ConfigureAwait(false);

Dapper - extracting single value already stored in local variable

I am using Dapper with a stored procedure.
public List<Sifrarnik> ChangeOpisText(string opis)
{
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["Cloud"].ConnectionString))
{
if (db.State == ConnectionState.Closed)
{
db.Open();
}
var response = db.Query<Sifrarnik>("dbo.spChangeOpisText #opis",
new
{
opis = opis
}).ToList();
return response;
}
}
I pass a single variable to the query and retrieve a single column/row from a database. This result is stored in the response variable.
But I don't know how to access the value and place it in a textbox. Any clues?
textbox1.Text = ?
For instance.. doing it for a combobox would be:
comboBox1.DataSource = response;
comboBox1.DisplayMember = "column-name";
comboBox1.ValueMember = "column-name";
When I check the type of the variable in prints List from the Data model I use for Dapper.
If you plan to retrieve a single row, why are you returning a list? Just return a single instance of Sifrarnik.
You can get the instance from the returned enumerable by using Single().
public Sifrarnik ChangeOpisText(string opis)
{
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["Cloud"].ConnectionString))
{
if (db.State == ConnectionState.Closed)
{
db.Open();
}
var response = db.Query<Sifrarnik>
(
"dbo.spChangeOpisText #opis",
new
{
opis = opis
}
)
.Single();
return response;
}
}

The XRSubreport does not contain any data when applying filter

I have two reports the first one 'RepGetAsemblyEmployeeForDailyReport' as master report and the second one 'RepDailyAssemblyProductionByEmployee' as detail report
on master report i added unbound detail band and I put in it XRSubreport and I set report source properties to detail report.i followed this instruction
Create a Master-Detail Report with Subreports
both reports has stored procedure as a datasource to open the master report i use this code
private async void DailyProductionByEmployee_Click(object sender, EventArgs e)
{
RepGetAsemblyEmployeeForDailyReport reportEmployee = new RepGetAsemblyEmployeeForDailyReport();
Parameter param1 = new Parameter
{
Name = "shifttime",
Type = typeof(string),
Visible = false,
Value = form.cmbShiftTime.EditValue
};
Parameter param2 = new Parameter
{
Name = "date",
Type = typeof(DateTime),
Visible = false,
Value = Convert.ToDateTime(form.FirstDate.EditValue)//.ToString("MM/dd/yyyy");
};
reportEmployee.Parameters.Add(param1);
reportEmployee.Parameters.Add(param2);
reportEmployee.DataSource = await assembly.RepGetAsemblyEmployeeForDailyReport(Convert.ToDateTime(form.FirstDate.EditValue).ToString("MM/dd/yyyy"),
Convert.ToInt32(form.cmbShiftTime.EditValue));
form.Close();
reportEmployee.ShowRibbonPreviewDialog();
}
to master report I use subreport BeforePrint event to set the datasource like so
private async void subRepProduction_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
((XRSubreport)sender).ReportSource.DataSource = await assembly.RepAssemblyDailyProductionShiftTimeByEmployee(Convert.ToDateTime(Parameters[1].Value).ToString("MM/dd/yyyy"),
Convert.ToInt32(Parameters[0].Value));
}
Now if I applying a filter I do not get any data
but when I clear the filter the some first rows does not show then all rows show then only the first row is repeated
How can I solve this problem, thanks in advance.
Update :Code that get data from sql server database
public async Task<DataTable> RepGetAsemblyEmployeeForDailyReport(string DateProduction, int ShiftTime)
{
DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
DataTable dt = new DataTable();
SqlParameter[] param = new SqlParameter[2];
param[0] = new SqlParameter("#Date", SqlDbType.NVarChar, 50)
{
Value = DateProduction
};
param[1] = new SqlParameter("#ShiftTime", SqlDbType.Int)
{
Value = ShiftTime
};
dt = await DAL.SelectData("RepGetAsemblyEmployeeForDailyReport", param);
DAL.Close();
return dt;
}
you cannot use "async void" event handlers here
because of "fire and forget approach".
remove the async/await keywords from the "subRepProduction_BeforePrint" event handler

Passing DropDownList SelectedValue to SQL Query throws Input String was not in a Correct Format

I'm working on an ASP.NET webforms page that queries the database for a list of entries in the Study table. These entries are to be passed into the dropdownlist. When a study is selected from the dropdownlist, the studyID is to be passed to the GetResponses method to retrieve associated data from a stored procedure.
I receive Input String was not in a Correct Format with the following snippets:
private DataTable LoadStudies(int iStudyID )
{
ddlStudies.Items.Clear();
ddlStudies.SelectedValue = "0";
DataTable dt = new DataTable();
using (PROTOTYPING db = new PROTOTYPING(ConfigurationManager.ConnectionStrings["SQL"].ConnectionString))
{
var query = (from d in db.Studies
where d.StudyStatus == 0 //Closed...
orderby d.StudyName
select new
{
d.StudyName,
d.StudyID,
});
if (query.Count() > 0)
{
foreach (var a in query)
{
ddlStudies.Items.Add(new ListItem(a.StudyID.ToString()));
}
}
dt.Dispose();
DataView dv = new DataView(dt);
return dt;
}
}
The error is thrown on the Page_Load which is currently written as follows:
protected void Page_Load(object sender, EventArgs e)
{
int iUserID = 0;
if (Session["UserID"] == null)
{
Response.Redirect("Default.aspx");
}
iUserID = Convert.ToInt32(Session["UserID"]);
int iRole = 0;
iRole = Convert.ToInt32(Session["RoleID"]);
if (!Page.IsPostBack)
{
LoadStudies(Convert.ToInt32(ddlStudies.SelectedValue));
GetResponses(Convert.ToInt32(ddlStudies.SelectedValue));
ddlStudies.DataSource = LoadStudies(Convert.ToInt32(ddlStudies.SelectedValue));
ddlStudies.DataTextField = "StudyName";
ddlStudies.DataValueField = "StudyID";
ddlStudies.DataBind();
}
}
How do I resolve the error, which is thrown when assigning the dropdownlist's DataSource to the LoadStudies method?
ddlStudies.SelectedValue is not a valid integer value 0,1,2 etc.
I would wager a guess it's an empty string. Convert.ToInt32(""), which will throw the exception you are experiencing.
Interestingly Convert.ToInt32(null) will return a zero.
Try
Convert.ToInt32(string.IsNullOrWhiteSpace(ddlStudies.SelectedValue) ? null : ddlStudies.SelectedValue)

Casting Linq to IEnumerable <Datarow>

I'm creating winForm app,In that Onbutton click i gather Data Tables from of Two database Mysql and Sqlite database.
I getting Casting error while on casting Linq query to IEnumerable to make fetch query values to DataTable to make display in DataGrid view.
private void button1_Click(object sender, EventArgs e)
{
var obj = new table1TableAdapter(); //Mysql Table Adapter
var obj2 = new Table1TableAdapter(); // Sqlite Table Adapter
var ds = new DataSet();
ds.Tables.Add(obj.GetData());
ds.Tables.Add(obj2.GetData());
var tab1 = ds.Tables[0];
var tab2 = ds.Tables[1];
var query = from o in tab1.AsEnumerable()
join od in tab2.AsEnumerable()
on o.Field<string>("Name") equals od.Field<string>("Name")
select new
{
Name = o.Field<string>("Name"),
Rollno = od.Field<Int64>("rollno"),
Book = o.Field<string>("Book")
};
var q2 = (IEnumerable<DataRow>)query; //Unable to cast object of type <JoinIterator>
DataTable orderTable = q2.CopyToDataTable();
dataGridView1.DataSource = orderTable;
}
Looking at your code, I'd say, why cast it to IEnumerable<DataRow> at all ? Just simply bind the query to your GridView.
dataGridView1.DataSource = query.ToList();
That's because the query object you are returning has no relation to DataRow. query is going to be an IEnumerable<SomeAnonymousType>. How is it expected to convert to DataRow?
You would need to alter your statement to make a DataRow:
select new DataRow(/* Whatever Params */) { /* More Params */ };
Then it's natively an IEnumerable<DataRow> and needs no casting.
Since your query is creating an IEnumerable you wouldn't be able to cast it to a DataRow. I also wouldn't not advise using select new DataRow(/* Whatever Params /) { / More Params */ }; since this would not be a true DataRow object and would be bad practice.
I would handle it this way. Even if this is a small project, there shouldn't be that much code in your Button_Click handler.
First, create a container object, call it a DTO or ViewModel. I suggest the later.
public class BookViewModel
{
public string Name { get; set; }
public Int64 Rollno { get; set; }
public string Book { get; set; }
}
Next, create a new class that will do your SQL queries. This will separate your Data Access logic from your form logic.
public class BookService
{
public IList<BookViewModel> GetBookViewModel()
{
var obj = new table1TableAdapter(); //Mysql Table Adapter
var obj2 = new Table1TableAdapter(); // Sqlite Table Adapter
var ds = new DataSet();
ds.Tables.Add(obj.GetData());
ds.Tables.Add(obj2.GetData());
var tab1 = ds.Tables[0];
var tab2 = ds.Tables[1];
var query = from o in tab1.AsEnumerable()
join od in tab2.AsEnumerable()
on o.Field<string>("Name") equals od.Field<string>("Name")
select new BookViewModel
{
Name = o.Field<string>("Name"),
Rollno = od.Field<Int64>("rollno"),
Book = o.Field<string>("Book")
};
return query.ToList();
}
}
Last, bind the List to your display.
private void button1_Click(object sender, EventArgs e)
{
BookService bookService = new BookService();
dataGridView1.DataSource = bookService.GetBookViewModel();
}
Now when you go back to make changes to your code, you will easily be able to modify your display logic and with out having to read through all of your intermixed code.
Example:
private void button1_Click(object sender, EventArgs e)
{
BookService bookService = new BookService();
IList<BookViewModel> books = bookService.GetBookViewModel();
if (books.Count == 0)
{
Label1.Text = "Sorry no books were found";
}
dataGridView1.DataSource = books;
}
For one thing, you're not going to be able to cast to an IEnumerable because you're query itself is not producing DataRows
select new
{
Name = o.Field<string>("Name"),
Rollno = od.Field<Int64>("rollno"),
Book = o.Field<string>("Book")
};
is creating an anonymous type.
You would have to change this to a DataRow somehow first, and then convert it to an IEnumerable.
I'm using the following statement and this works for me
UC070_WizardStepFilesDataSet.AllDossierDetailResultsRow[] searchrows =
(from a in _wizardStepPreviewDataSet.AllDossierDetailResults
where a.WingsSetNbr == row.WingsSetNbr && !a.BookCode.StartsWith("V")
select a).ToArray<UC070_WizardStepFilesDataSet.AllDossierDetailResultsRow>();

Categories

Resources