Insert multiple checked values from gridview into Database - sql

I have this methode to loop through if the data in my gridview is checked or not, if they are checked they should be inserted into the database.
As you can see the only data I want to insert from the gridview is the text from cell[2] in the gridview and it's in the name of #HeaderName
using (SqlConnection con = new SqlConnection("my con string"))
{
con.Open();
foreach (GridViewRow row in GridViewConsNames.Rows)
{
CheckBox myCheckBox = row.FindControl("myCheckBox") as CheckBox;
if (myCheckBox.Checked)
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Accounting_Consolidation_ServiceOutputs(Cusomer_Name, Service_Name, Header_Name, Sort_Postion, Rename_to, Value) Values(#CustName,#ServiceName,#HeaderName,#Sort,#Rename,#Value)", con))
{
//cmd.Parameters.AddWithValue("PersonId", Convert.ToInt32(GridViewConsNames.DataKeys[row.RowIndex].Value));
cmd.Parameters.AddWithValue("#CustName", TextBoxCustName.Text);
cmd.Parameters.AddWithValue("#ServiceName", DropDownListServicesAvailable2.SelectedItem.Text);
cmd.Parameters.AddWithValue("#HeaderName", "Name of the checked cells from my gridview");
cmd.Parameters.AddWithValue("#Sort", null);
cmd.Parameters.AddWithValue("#Rename", "");
cmd.Parameters.AddWithValue("#Value", null);
cmd.ExecuteNonQuery();
}
}
}
}
I have tried with this
GridViewRow row = GridViewConsNames.SelectedRow;
string headername = row.Cells[2].Text;
But this seems not working

Why do you use GridViewRow row = GridViewConsNames.SelectedRow when you actually want to use all rows where the checkbox is selected?
So i guess that this is what you want:
foreach (GridViewRow row in GridViewConsNames.Rows)
{
CheckBox myCheckBox = row.FindControl("myCheckBox") as CheckBox;
if (myCheckBox.Checked)
{
// ...
string headerName = row.Cells[2].Text;
cmd.Parameters.AddWithValue("#HeaderName", headerName);
// ...
}
}

Related

Font style in DataRow ASP.NET Core

I was trying to change the font size on specific row cell depends on what length the string is by using DataRow, using DataGridView I get an error, same with the DataGrid. How can I manipulate the cell in every row using DataRow?
DataTable dt = new DataTable();
using (SqlDataAdapter da = new SqlDataAdapter("Command Here"))
{
da.Fill(dt);
foreach (DataRow asd in dt.Rows)
{
if (asd[4].ToString().Length >= 45)
{
asd[4] = "test";
}
}
}
I know using = is setting a new value for that column cell, but I was trying to manipulate its style.

Xamarin DataGridView Value pass to another Page Textbox

i would like to request you that kindly help me how to pass the value from Xamarin DataGridView selected row to another page TextBox. please see the mention below of my code.
This is my code to fill the DatGridView:
private void Bind_GVhkCL(string text)
{
{
string query = "SELECT Room_No as 'Room No',Room_Status as 'Room Status', S_Time as 'Start Time',E_Time as 'End Time',c_date as 'Create Date'from HK_Chk " + text;
sqlConnection.Open();
SqlDataAdapter da = new SqlDataAdapter(query, sqlConnection);
DataTable dt = new DataTable();
da.Fill(dt);
GVhkCL.ItemsSource = dt;
//GVhkCL.RowHeight = 60;
sqlConnection.Close();
}
}
This is code that I am trying to pass the value to another form or you can give me any other idea:
private void DataGridView_DoubleTap(object sender, DataGridGestureEventArgs e)
{
if (e.Item != null)
{
var editForm = new EditFormPage(GVhkCL, GVhkCL.GetItem(e.RowHandle),
(DataTemplate)Resources["Room No"]);
Navigation.PushAsync(editForm);
}
}

How to populate another combobox by selecting value from previous one (cascading)?

I'm having a bit of a problem when trying to populate cascading comboboxes. First part works great, the first combobox gets filled.
Here is the code:
private void LoadCombo()
{
try
{
SqlConnection conn = new SqlConnection(#"Data source=SERVER\SOURCE;Initial Catalog=MyDatabase; Integrated security=true;");
conn.Open();
SqlDataAdapter da = new SqlDataAdapter("select name from sys.tables where type = 'U'", conn);
DataTable dt = new DataTable();
foreach (DataRow row in dt.Rows)
{
comboBox1.Items.Add(row["name"].ToString());
}
}
catch (Exception ex)
{
throw ex;
}
}
Now, all table names are loaded in comboBox1. Now, here's the main problem: I'm trying to retrieve table name from comboBox1 and use the text to pass another query to SQL Server, so that, when I make a selection in comboBox 1, comboBox 2 gets filled with table properties of a specified column of a called table.
Here is the code:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(#"Data source=SERVER\SOURCE;Initial Catalog=MyDatabase; Integrated security=true;");
SqlDataAdapter da = new SqlDataAdapter("select distinct ColumnName from'" + comboBox1.Text + "'", conn);
DataTable dt = new DataTable();
da.Fill(dt);
foreach (DataRow row in dt.Rows)
{
comboBox2.Items.Add(row["ColumnName"].ToString());
}
}
catch (Exception ex)
{
throw ex;
}
}
I've been getting an error
Syntax error near columnName
How do I fix this problem? Thank you!

Passing DropDownList value into SQL command in ASP.net

I have a DropDownList which gets it values from SQL table
I want to get the Average of the selected item (course in this case) from the dropDownList and to show it in a label :
This section works -
SqlConnection sqlConnection1;
sqlConnection1 = new SqlConnection(#"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
SqlCommand Command = null;
Command = new SqlCommand("SELECT Course FROM GradesTable1", sqlConnection1);
Command.Connection.Open();
SqlDataAdapter dataAdapter = new SqlDataAdapter(Command);
DataTable dataTble1 = new DataTable();
dataAdapter.Fill(dataTble1);
if (dataTble1.Rows.Count > 0)
{
foreach (DataRow row in dataTble1.Rows)
{
ListItem course1 = new ListItem(row["Course"].ToString());
if (!DropDownList1.Items.Contains(course1))
{
DropDownList1.Items.Add(course1); // showing the 2 courses
}
}
}
Command.Connection.Close();
}
}
Here is the problem - (I get nothing, no data )
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
SqlConnection sqlConnection1;
sqlConnection1 = new SqlConnection(#"Data Source=HA\SQLEXPRESS; Initial Catalog=Grades1; Integrated Security=True");
SqlCommand Command = null;
Command = new SqlCommand($"SELECT AVG(Grade) FROM GradesTable1 WHERE Course = #course", sqlConnection1);
Command.Parameters.AddWithValue("#course", DropDownList1.SelectedItem);
Command.Connection.Open();
SqlDataReader sqlDataReader1 = Command.ExecuteReader();
if (sqlDataReader1.Read())
{
LabelAverage.Text = sqlDataReader1[0].ToString();
}
else
{
LabelAverage.Text = "No Data"; // doesn't get into here anyhow
}
}
EDIT
I tried several variations as $"SELECT AVG(Grade) AS "ClassAVG" FROM GradesTable1 WHERE Course = #course" and Command.Parameters.AddWithValue("#course", DropDownList1.SelectedItem.Text), or DropDownList1.SelectedValue
I believe the problem is with the DropDownlist values which being received from the SQL and are not hard coded.
Is there a correct way to this? is it possible without knowing what are the "Courses" in advanced?
Thanks for the answers, feel free to give your opinion.
I found out what was missing in the DropDownList in aspx page (not the aspx.cs page) -the AutoPostBack="true"
Adding that to DropDownList solved the problem.
// query = Sql query
query.Select(s => new MusteriNoktaComboItemDTO
{
Label = s.Adi,
Value = s.ID.ToString()
}).ToList();

The data isn't being loaded into datagrid view. What am i missing?

I think this is one of those times where I'm looking at the code and it all seems fine because my eye's think it will be. I need a fresh set of eyes to look at this code and tell me way it's not loading into the first datagrid view. Thank you for any help your able to provide.
private DataSet DataSetRentals { get; set; }
public DataRelationForm()
{
InitializeComponent();
}
private void DataRelationForm_Load(object sender, EventArgs e)
{
DataSet relationship = new DataSet("relationship");
/////
SqlConnection conn = Database.GetConnection();
SqlDataAdapter adapter = new SqlDataAdapter("Select * From Car", conn);
DataSet DataSetRentals = new DataSet("Relationship");
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Car");
adapter.Fill(DataSetRentals, "Car");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Car");
DataTable Car;
Car = DataSetRentals.Tables["Car"];
foreach (DataRow drCurrent in Car.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
////////////////////////////////////
SqlDataAdapter adapter2 = new SqlDataAdapter("Select * From CarRental", conn);
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Rentals");
adapter.Fill(DataSetRentals, "Rentals");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Rentals");
DataTable CarRental;
CarRental = DataSetRentals.Tables["Rentals"];
foreach (DataRow drCurrent in CarRental.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
/////
SqlDataAdapter adapter3 = new SqlDataAdapter("Select * From Customer", conn);
adapter.FillSchema(DataSetRentals, SchemaType.Source, "Customer");
adapter.Fill(DataSetRentals, "Customer");
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey;
adapter.Fill(DataSetRentals, "Customer");
DataTable Customer;
Customer = DataSetRentals.Tables["Customer"];
foreach (DataRow drCurrent in Customer.Rows)
{
Console.WriteLine("{0} {1}",
drCurrent["au_fname"].ToString(),
drCurrent["au_lname"].ToString());
}
////////////////////////
DataSetRentals.Tables.Add(Customer);
DataSetRentals.Tables.Add(CarRental);
DataSetRentals.Tables.Add(Car);
DataRelation Step1 = new DataRelation("Customer2CarR",
Customer.Columns["CustomerNo"], CarRental.Columns["CustomerNo"]);
DataSetRentals.Relations.Add(Step1);
DataRelation Step2 = new DataRelation("CarR2Car",
Car.Columns["CarID"], CarRental.Columns["CarID"]);
DataSetRentals.Relations.Add(Step2);
////////////////////////
CustomerGrid.DataSource= DataSetRentals.Tables["Customer"];
CarRGrid.DataSource = DataSetRentals.Tables["CarRental"];
CarGrid.DataSource = DataSetRentals.Tables["Car"];
CustomerGrid.SelectionChanged += new EventHandler(Customer_SelectionChanged);
CarRGrid.SelectionChanged += new EventHandler(CarR_SelectionChanged);
}
private void Customer_SelectionChanged(Object sender, EventArgs e)
{
if (CustomerGrid.SelectedRows.Count > 0)
{
DataRowView selectedRow =
(DataRowView)CustomerGrid.SelectedRows[0].DataBoundItem;
DataSetRentals.Tables["CarRental"].DefaultView.RowFilter =
"CustomerNo = " + selectedRow.Row["CustomerNo"].ToString();
}
else
{
}
}
private void CarR_SelectionChanged(Object sender, EventArgs e)
{
if (CarRGrid.SelectedRows.Count > 0)
{
DataRowView selectedRow =
(DataRowView)CarRGrid.SelectedRows[0].DataBoundItem;
DataSetRentals.Tables["Car"].DefaultView.RowFilter =
"CarID = " + selectedRow.Row["CarID"].ToString();
}
}
And this is the code for the Database.GetConnection() method:
SqlConnectionStringBuilder stringBuilder = new SqlConnectionStringBuilder();
bool OnUni;
OnUni = (System.Environment.UserDomainName == "SOAC") ? true : false;
stringBuilder.DataSource = (OnUni) ? #"SOACSQLSERVER\SHOLESQLBSC" : "(local)";
stringBuilder.InitialCatalog = "CarRental_P117365";
stringBuilder.IntegratedSecurity = true;
return new SqlConnection(stringBuilder.ConnectionString);
It looks like you may have forgotten to call SqlConnection.Open() to actually open the connection. I would also recommend wrapping your connection in a using and explicitly calling SqlConnection.Close() at the end of it, so you don't accidentally leave it open:
using(SqlConnection conn = Database.GetConnection())
{
conn.Open();
/*
rest of code here
*/
conn.Close();
}
For some other good information/examples of properly opening/disposing of SqlConnections, you can also take a look at these SO questions:
Close and Dispose - which to call?
Do I have to Close() a SQLConnection before it gets disposed?
in a "using" block is a SqlConnection closed on return or exception?
youre not binding your data to any datasoruce.
try something like this
using(SqlConnection conn = Database.GetConnection())
try
{
{
------your code here up to DataTable Car-----
DataTable Car;
Car = DataSetRentals.Tables["Car"];
gridview.Datasource = Car;
}
}
catch (SqlException sqlex )
{
string msg = "Fetch Error:";
msg += sqlex.Message;
throw new Exception(msg);
}
Theres no need to open or close the SQL connection as this is done using the using statement at the top where it opens, and when its finishes closes \ disposes of the connection