I am currently getting this error when trying to select a date from a drop down list, once the date is selected it should Display data in a GridView depending on the drop down list value. This is achieved using a 'Where' statement equals the value of the selected index.
I understand that it is a problem with the way the dates are being displayed in the drop down list, as opposed to the way they are saved in the database. So I have tried to swap the format from dd/mm/yyyy to yyyy/mm/dd in the drop down list, to see if this fixes the problem. But I can't seem to get it to work.
Please can someone recommend a fix to this?
Drop Down List selected index change C# :
protected void DropDownList2_SelectedIndexChanged(object sener, EventArgs e)
{
String query = "SELECT Stock_Take.Username, Item.ItemID, Item.ItemDesc, Stock_Take_Item.BarQuantity, Stock_Take_Item.StorageQuantity, Stock_Take.StockTakeIDNew FROM Item INNER JOIN Stock_Take_Item ON Item.ItemID = Stock_Take_Item.ItemID INNER JOIN Stock_Take ON Stock_Take_Item.StockTakeIDNew = Stock_Take.StockTakeIDNew where Stock_Take.Username = #USER AND Stock_Take.StockDate = #DATE";
SqlConnection con = new SqlConnection(#"Data Source=(local)\;Initial Catalog=SmallBatch;Integrated Security=True;");
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#USER", SqlDbType.VarChar).Value = DropDownList1.SelectedValue;
cmd.Parameters.Add("#DATE", SqlDbType.DateTime).Value = DropDownList2.SelectedValue;
// DateTime date = Convert.ToDateTime(DropDownList2.SelectedValue.ToString());
SqlDataReader reader = cmd.ExecuteReader();
GridView1.DataSource = reader;
GridView1.DataBind();
con.Close();
}
Binding the dates from the database to the drop down list C# code:
private void BindDropDownList2(String field)
{
DataTable dataTable = new DataTable();
SqlConnection con = new SqlConnection(#"Data Source=(local)\;Initial Catalog=SmallBatch;Integrated Security=True;");
try
{
con.Open();
String Query = "Select StockDate, StockTakeIDNEW from Stock_Take WHERE Username = #Value1";
SqlCommand sqlCmd = new SqlCommand(Query, con);
sqlCmd.Parameters.AddWithValue("#Value1", field);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dataTable);
if (dataTable.Rows.Count > 0)
{
DropDownList2.DataSource = dataTable;
DropDownList2.DataTextField = "StockDate";
DropDownList2.DataValueField = "StockTakeIDNew";
// DropDownList2.DataTextFormatString = "(yyyy/MM/dd}";
DropDownList2.DataBind();
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error";
msg += ex.Message;
*I also have another drop down list, that a user selects a Username from, which in turn affects what dates are shown in the DropDownList2
Here:
cmd.Parameters.Add("#DATE", SqlDbType.DateTime).Value = DropDownList2.SelectedValue;
manually parse the value first, so it is a DateTime:
var date = DateTime.Parse(DropDownList2.SelectedValue); // TODO: replace with format etc
cmd.Parameters.Add("#DATE", SqlDbType.DateTime).Value = date;
Related
I have a DropDownList that gets populated by a SQL Server table called tblVisa. My issue is that the values that are being populated from the SQL Server table are not being saved. Everything else gets saved except for my DropDownLists. I've tried using .SelectedValue and .Text, but it still does not work.
Here is my code
protected void PopulateVisaType()
{
List<ListItem> result = new List<ListItem> { new ListItem("", "") };
SqlCommand cmd = new SqlCommand() { Connection = sqlConn, CommandText = "SELECT VisaType FROM tblVisa ORDER BY VisaType ASC" };
if (sqlConn.State == ConnectionState.Closed)
{
sqlConn.Open();
}
SqlDataReader read = cmd.ExecuteReader();
while (read.Read())
{
result.Add(new ListItem(read["VisaType"].ToString(), read["VisaType"].ToString()));
}
read.Close();
sqlConn.Close();
cmd.Dispose();
DDLVisa.DataSource = result;
DDLVisa.DataValueField = "value";
DDLVisa.DataTextField = "text";
DDLVisa.DataBind();
}
Here's my code for saving the information into the database:
protected void LbSaveProfile_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand() { Connection = sqlConn, CommandText = "spSaveNewProviderInformation", CommandType = CommandType.StoredProcedure };
if (sqlConn.State == ConnectionState.Closed)
{
sqlConn.Open();
}
cmd.Parameters.AddWithValue("#EmployeeNumber", TbEmployeeNumber.Text.Trim());
cmd.Parameters.AddWithValue("#SSN", TbSSN.Text.Trim());
cmd.Parameters.AddWithValue("#ContractType", DDLContractType.SelectedItem.Value);
cmd.Parameters.AddWithValue("#Firstname", TbFirstname.Text.Trim());
cmd.Parameters.AddWithValue("#Lastname", TbLastname.Text.Trim());
cmd.Parameters.AddWithValue("#MiddleInitial", TbMiddleInitial.Text.Trim());
cmd.Parameters.AddWithValue("#ContractRenewalDate", TbContractRenewalDate.Text.Trim());
cmd.Parameters.AddWithValue("#Position", DDLPosition.Text.Trim());
cmd.Parameters.AddWithValue("#Specialty", DDLSpecialty.Text.Trim());
cmd.Parameters.AddWithValue("#PrimaryDepartment", DDLPrimaryDepartment.Text.Trim());
cmd.Parameters.AddWithValue("#SecondaryDepartment", DDLSecondaryDepartment.Text.Trim());
cmd.Parameters.AddWithValue("#Gender", DDLGender.Text.Trim());
cmd.Parameters.AddWithValue("#Birthdate", TbBirthdate.Text.Trim());
cmd.Parameters.AddWithValue("#EmailAddress", TbEmailAddress.Text.Trim());
cmd.Parameters.AddWithValue("#PhoneNumber", TbPhoneNumber.Text.Trim());
cmd.Parameters.AddWithValue("#Address", TbAddress.Text.Trim());
cmd.Parameters.AddWithValue("#PassportNumber", TbPassportNumber.Text.Trim());
cmd.Parameters.AddWithValue("#Citizenship", DDLCitizenship.Text.Trim());
cmd.Parameters.AddWithValue("#Visa", DDLVisa.Text.Trim());
cmd.Parameters.AddWithValue("#Status", 1);
cmd.ExecuteNonQuery();
sqlConn.Close();
Alert("Provider Information saved!");
ClearControls();
}
You much better to provide the drop down list with column names.
So, say this:
protected void PopulateVisaType()
{
SqlConnection sqlConn = new SqlConnection("");
using (SqlCommand cmd = new SqlCommand("SELECT VisaType FROM tblVisa ORDER BY VisaType ASC", sqlConn))
{
if (sqlConn.State == ConnectionState.Closed)
{
sqlConn.Open();
}
DDLVisa.DataSource = cmd.ExecuteReader();
DDLVisa.DataValueField = "VisaType";
DDLVisa.DataTextField = "VisaType";
DDLVisa.DataBind();
//DDLVisa.Items.Insert(0, new ListItem("")); // optional blank row choice
sqlConn.Close();
}
}
So the TextField, and the DataText field need to be a named column from the data source.
I also included an optional first blank option if you need/want/expect to have no choice.
However, keep in mind that this empty string should be translated into a null in your database if you don't allow (or want) empty strings, and want a null for that value. This applies to all of your values. (perhaps the stored procedure does this?).
I have established connection and inserted values into the table.
However, I am not sure the best method to refresh the DataGridview as the values have been inserted after click button.
private void button1_Click(object sender, EventArgs e)
{
{
string theText = makeTextBox.Text;
string theText2 = modelTextBox.Text;
var value = Convert.ToInt32(yearTextBox.Text);
int i = 6;
cnn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "INSERT INTO cars(Make,Model,Year) VALUES(#Make,#Model,#Year)";
cmd.Prepare();
cmd.Parameters.AddWithValue("#Make", theText);
cmd.Parameters.AddWithValue("#Model", theText2);
cmd.Parameters.AddWithValue("#Year", value);
cmd.ExecuteNonQuery();
{
}
dataGridView1.DataSource = carsBindingSource;
dataGridView1.Refresh();
cnn.Close();
}
}
}
}
enter image description here
EDIT:
here is the code with the working solution of rebinding the datasource and then it will update:
{
string theText = textBox1.Text;
string theText2 = textBox2.Text;
var value = Convert.ToInt32(textBox3.Text);
int i = 6;
cnn.Open();
MySqlCommand cmd = new MySqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "INSERT INTO cars(Make,Model,Year) VALUES(#Make,#Model,#Year)";
cmd.Prepare();
cmd.Parameters.AddWithValue("#Make", theText);
cmd.Parameters.AddWithValue("#Model", theText2);
cmd.Parameters.AddWithValue("#Year", value);
cmd.ExecuteNonQuery();
{
}
cnn.Close();
carsBindingSource = new BindingSource();
carsBindingSource.DataSource = carsTableAdapter.GetData();
dataGridView2.DataSource = carsBindingSource;
}
}```
Your code is missing the part where the carsBindingSource variable is initialized with data. From your limited code, it should be noted that… if you add/insert a new row into the table in the data base, then this is NOT going to automatically update the carsBindingSource.
It is unknown “what” is used as a DataSource to the carsBindingSource. OR, how this data source is populated. I will assume the DataSource to the BindingSource is a DataTable and that somewhere in the code it is getting this DataTable from a query to the data base. If this process is not already in a single method that returns a DataTable, then, I recommend you create one, and it may look something like…
private DataTable GetCarsDT() {
DataSet ds = new DataSet();
string connString = "Server = localhost; Database = CarsDB; Trusted_Connection = True;";
try {
using (SqlConnection conn = new SqlConnection(connString)) {
conn.Open();
using (SqlCommand command = new SqlCommand()) {
command.Connection = conn;
command.CommandText = "SELECT * FROM Cars";
using (SqlDataAdapter da = new SqlDataAdapter(command)) {
da.Fill(ds, "Cars");
return ds.Tables[0];
}
}
}
}
catch (Exception ex) {
MessageBox.Show("DBError:" + ex.Message);
}
return null;
}
Above will return a DataTable with three (3) columns, Make, Model and Year. This DataTable is used as a DataSource to the BindingSource… carsBindingBource.
Now in the button1_Click event, the code inserts the new values into the data base. However, the carsBindingSource will still contain the data “before” the new items were added to the DB. Therefore, we can simply use the method above to “update” the carsBindingSource after the new items are added to the DB.
Note: you can go two routs here, 1) as described above, simply update “all” the data in the binding source… OR … 2) after updating the new items into the data base, you can also add the new items to the binding source’s data source… i.e. its DataTable. Either way will work and unless there is a large amount of data, I do not think one way would be preferred over the other.
Below shows what is described above. Note, the commented code adds the new items directly to the DataTable. You can use either one but obviously not both.
private void button1_Click(object sender, EventArgs e) {
string connString = "Server = localhost; Database = CarsDB; Trusted_Connection = True;";
try {
using (SqlConnection conn = new SqlConnection(connString)) {
conn.Open();
using (SqlCommand command = new SqlCommand()) {
command.Connection = conn;
command.CommandText = "INSERT INTO cars(Make,Model,Year) VALUES(#Make,#Model,#Year)";
command.Parameters.Add("#Make", SqlDbType.NChar, 50).Value = makeTextBox.Text.Trim();
command.Parameters.Add("#Model", SqlDbType.NChar, 50).Value = modelTextBox.Text.Trim();
int.TryParse(yearTextBox.Text.Trim(), out int year);
command.Parameters.Add("#Year", SqlDbType.Int).Value = year;
command.ExecuteNonQuery();
carsBindingSource.DataSource = GetCarsDT();
//DataTable dt = (DataTable)carsBindingSource.DataSource;
//dt.Rows.Add(makeTextBox.Text.Trim(), modelTextBox.Text.Trim(), year);
}
}
}
catch (Exception ex) {
MessageBox.Show("DBError:" + ex.Message);
}
}
Putting all this together…
BindingSource carsBindingSource;
public Form1() {
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e) {
carsBindingSource = new BindingSource();
carsBindingSource.DataSource = GetCarsDT();
dataGridView1.DataSource = carsBindingSource;
}
Hope this makes sense.
I dont think its possible. You may need to create a separate button to submit and then refresh the data
I have 2 datagridviews now i want to select a column named "Name" in the first datagridview and us it as the WHERE in my query to Select values from a table and put it in the other datagridview.
SqlCommand cmd = new SqlCommand();
cmd = ss.CreateCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
ss.Open();
cmd.CommandType = CommandType.Text;
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '" +
row.Cells[4].Value.ToString() + "' ";
cmd.CommandText = Query;
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter dp = new SqlDataAdapter(cmd);
dp.Fill(dt);
dgvSign.DataSource = dt;
ss.Close();
}
but it gives me error when there is null and it is only selecting the first row in the first datagridview.
You create in each foreach-loop a new DataTable and therefore it will always just have one Value. So you have to create it before the foreach-loop.
And make sure you check the Values you want to use before using them.
With this easy if-condition, there won't be any problems.
Edit1:
This code snippet is working just fine.
Just change the ConnectionString and you are done.
DataTable dt = new DataTable();
string error;
using (SqlConnection con = new SqlConnection(#"Data Source=SERVER;Initial Catalog=DATEBASE; User ID=USERNAME; Password=PASSWORD"))
{
SqlCommand cmd = new SqlCommand();
foreach (DataGridViewRow row in dgvAtt.Rows)
{
string Query = "SELECT Signature FROM TBL_Student WHERE Name = '";
if (row.Cells.Count >= 4 && row.Cells[4].Value != null)
{
Query += row.Cells[4].Value.ToString();
}
Query += "'";
try
{
cmd = new SqlCommand(Query, con);
if (con.State == ConnectionState.Closed)
con.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
adapter.Fill(dt);
}
catch (Exception ex)
{
error = ex.Message;
}
}
}
dgvSign.DataSource = dt;
I have a strange problem,
I'm working with win-form which is coding in c#..and sql server
In a form I have a Combo-box which is collected data by the database(say 1).
and later I have to Insert that particular value/member details into another database(say 2)
Here My problem raises,,Once My combo-box any value is inserted into 2nd database,that particular value/member should not visible in the combo-box for the next time on the same day..
Of course Here I'm using datetimepicker..
Here I'm using following code...and Of-course it is wrong..Please Help me
SqlCommand cmd1 = new SqlCommand("select employee_id,Empployee_Name,date from dailyattendance", cn);
SqlDataReader sdr;
DataTable dt = new DataTable();
sdr = cmd1.ExecuteReader();
if (sdr.Read())
{
string employeeid = (string)sdr["employee_id"];
string employeename = (string)sdr["Empployee_Name"];
string date = (string)sdr["date"];
try
{
//cn.Open();
SqlCommand cmd = new SqlCommand("select employee_id,employee_name from Employee_Details", cn);
SqlDataReader sdr1;
DataTable dt1=new DataTable();
sdr1 = cmd.ExecuteReader();
dt1.Load(sdr1);
if (sdr1.Read())
{
string date1=dateTimePicker1.Value.ToString("dd/MM/yyyy");
if ()//here the main problem
{
string employeeid1 = (string)sdr1["employee_id"];
string employeename1 = (string)sdr1["employee_name"];
comboBox1.DisplayMember = employeeid1;
comboBox1.DisplayMember = employeename1;
comboBox1.DataSource=dt1;
cn.Close();
}
}
ConnectionStringSettings consettings = ConfigurationManager.ConnectionStrings["attendancemanagement"];
string connectionString = consettings.ConnectionString;
SqlConnection cn = new SqlConnection(connectionString);
cn.Open();
try
{
string dtp = dateTimePicker1.Value.ToString("dd/MM/yyyy");
string query = "select employee_id,employee_name,image_of_employee,image_path from Employee_Details where employee_id not in (select employee_id from dailyattendance where date = '" + dtp + "')";//Here added a new query which is working
SqlCommand cmd = new SqlCommand(query, cn);
SqlDataReader dtr;
dtr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dtr);
foreach (DataRow row in dt.Rows)
{
var name = (string)row["employee_name"];
row["employee_name"] = name.Trim();
}
comboBox1.ValueMember = "employee_id";
comboBox1.DisplayMember = "employee_name";
listBox1.ValueMember = "employee_id";
listBox1.DisplayMember = "employee_name";
comboBox1.DataSource = dt;
listBox1.DataSource = dt;
comboBox1.SelectedItem = null;
listBox1.SelectedItem = null;
cn.Close();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
Simply at query added some workable logic
I am trying to delete selected data from datagrid and database at the same time when user clicks on "Delete". It is not working and error message shows that "Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index"
Can anyone help me out this coding.
private void btnDeleteCustomer_Click(object sender, EventArgs e)
{
string strSqlConnection = #"Data Source = KK\SQLEXPRESS; Integrated Security = SSPI; Initial Catalog = JeanDB";
if ((dgvCustomerView.Rows.Count>0) && (dgvCustomerView.SelectedRows[1].Index != dgvCustomerView.Rows.Count))
{
SqlConnection sqlconn = new SqlConnection(strSqlConnection);
DataSet dsCustomers = new DataSet();
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = #iCustomerID";
SqlDataAdapter sdaCustomer = new SqlDataAdapter(QueryDelCus, sqlconn);
sqlconn.Open();
DataTable dtEmployee = new DataTable("Customers");
sdaCustomer.Fill(dsCustomers, "Customers");
sqlconn.Close();
dgvEmpView.Rows.RemoveAt(dgvEmpView.SelectedRows[0].Index);
MessageBox.Show("Deleted Successfully");
}
}
Instead of Remove you can rebind grid:
dgvEmpView.DataSource = dsCustomers;
dgvEmpView.DataBind();
MessageBox.Show("Deleted Successfully");
and for deletion ExecuteNonQuery is used:
SqlCommand cmd = new SqlCommand(QueryDelCus, sqlconn);
sqlconn.Open();
cmd.ExecuteNonQuery();
Unless you have two rows selected referencing the SelectedRows[1] is wrong. The array indexes start always with zero. (Probably it is just a type because the other lines references correctly the row to be deleted)
if ((dgvCustomerView.Rows.Count>0) &&
(dgvCustomerView.SelectedRows[0].Index != dgvCustomerView.Rows.Count))
{
....
but then, to delete the row in the database, you don't need to use an SqlDataAdapter.
You could work directly with a SqlCommand
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = #iCustomerID";
SqlCommand cmd = new SqlCommand(QueryDelCus, sqlconn);
cmd.Parameters.AddWithValue("#iCustomerID", iCustomerID);
sqlconn.Open();
cmd.ExecuteNonQuery();
finally you could simply remove the selected row from the grid without further query
dgvEmpView.Rows.RemoveAt(dgvEmpView.SelectedRows[0].Index);
If do not use sql parameters then use plain sql query.
DataSet dsCustomers = new DataSet();
int iCustomerID = Convert.ToInt32(dgvEmpView.SelectedRows[0].Cells[0].Value.ToString());
string QueryDelCus = #"Delete from dbo.Customers WHERE CustomerID = "+ iCustomerID.ToString();
SqlDataAdapter sdaCustomer = new SqlDataAdapter(QueryDelCus, sqlconn);