Sql command doesn't display table - c#

I have this code behind button that displays table in SQL when the button is pressed.
I cant seem to know that problem why it doesn't display any table?
I added this line of code to check if the BatchID is out of range in the sql table
if (read.Read())
{
GridView1.DataSource = read;
GridView1.DataBind();
}
else
{
lbl_NoBatchID.Text = "BatchID out of range";
}
protected void Button1_Click(object sender, EventArgs e)
{
if (DropDownList1.SelectedItem.ToString() =="ER00 - File Header")
{
using (SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["DBcon"]))
{
if (String.IsNullOrEmpty(TextBox_ID.Text.ToString()))
{
lbl_NoBatchID.Text = "Please enter BatchID!";
}
else
{
try
{
lbl_NoBatchID.Text = "";
SqlCommand sqlCommand = new SqlCommand("Select * from tbl_WinApps_FileHeader Where BatchID =" + TextBox_ID.Text.ToString());
sqlCommand.Connection = con;
con.Open();
SqlDataReader read = sqlCommand.ExecuteReader();
if (read.Read())
{
GridView1.DataSource = read;
GridView1.DataBind();
}
else
{
lbl_NoBatchID.Text = "BatchID out of range";
}
}
catch (Exception)
{
}
}
}
}

Make sure you do two things.
1.) Close the DataReader after Databind().
2.) Set AutoGenerateColumns="True" for your GridView.

Related

Delete a row from a table, specified by the user, with the click of a button in C#

I am using Visual Studio 2019 Winforms C# .NET Framework and in the Winforms project, there is a textbox and a button.
When I type a parameter name in the textbox and click the button, I want to delete the row from the table called "Serial_Key".
private void button1_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString;
SqlConnection sqlconn2 = new SqlConnection(mainconn);
string sqlquery = "select * from [dbo].[Serial-Keys] where Serial_Key=#Serial_Key";
sqlconn2.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn2);
sqlcomm.Parameters.AddWithValue("#Serial_Key", SerialKeyBox.Text);
SqlDataAdapter sda = new SqlDataAdapter(sqlcomm);
DataTable dt = new DataTable();
sda.Fill(dt);
sqlcomm.ExecuteNonQuery();
if (dt.Rows.Count > 0)
{
Cursor.Current = Cursors.WaitCursor;
try
{
}
catch (Exception)
{
}
Cursor.Current = Cursors.Default;
}
else
{
MessageBox.Show("Invalid Serial Key!");
label7.Text = "Serial Key Rejected...";
}
}
Change your select statement to a delete statement and remove all the DataAdaptor stuff as thats only required if you are querying records.
private void button1_Click(object sender, EventArgs e)
{
string mainconn = ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString;
SqlConnection sqlconn2 = new SqlConnection(mainconn);
// Use a Delete statement, not a select
string sqlquery = "delete from [dbo].[Serial-Keys] where Serial_Key = #Serial_Key";
sqlconn2.Open();
SqlCommand sqlcomm = new SqlCommand(sqlquery, sqlconn2);
// Construct the parameter yourself with the correct datatype and precision
sqlcomm.Parameters.Add(new SqlParameter("#Serial_Key", SqlDbType.VarChar, 32) { Value = SerialKeyBox.Text });
// Remove all the DataAdaptor stuff
// ExecuteNonQuery returns the rows affected
int numberOfRecords = sqlcomm.ExecuteNonQuery();
if (numberOfRecords > 0)
{
// Any code to run on an effective delete
}
else
{
MessageBox.Show("Invalid Serial Key!");
label7.Text = "Serial Key Rejected...";
}
}
If you install Dapper then your code becomes very simple:
private async void button1_Click(object sender, EventArgs e)
{
using(var c = new SqlConnection(_connStr))
await c.ExecuteAsync("DELETE FROM dbo.[Serial-Keys] WHERE serial_key = #sk", new { sk = SerialKeyBox.Text });
}
And, bonus, it doesn't jam your UI while it runs queries
I recommend you put that string mainconn = ConfigurationManager.ConnectionStrings["Myconnection"].ConnectionString; into a class level variable called _connStr instead, to help tidy things up
http://dapper-tutorial.net (no affiliation)

How to update items from datagridview in c#

I want to update invoice and invoice has multiple items i retrieve invoice items from Database to DataGridView now user can remove the items and can add the items and user will click on update button to update the invoice in database.
My Code:
try
{
using (SQLiteConnection con = new SQLiteConnection(AppSettings.ConnectionString()))
{
con.Open();
for (int j = 0; j < dgv.Rows.Count; j++)
{
using (SQLiteCommand sc = new SQLiteCommand("Update Orders Set [Order_No] = #Order_No,[Order_Type] = #Order_Type,[Order_Date] = #Order_Date,[Customer_Name] = #Customer_Name,[Contact] = #Contact,[Adress] = #Adress,[Delivery_Address] = #Delivery_Address,[Rider] = #Rider,[Items] = #Items,[Price] = #Price,[Qty] = #Qty,[Item_Total] = #Item_Total,[Item_Cat] = #Item_Cat,[SubTotal] = #SubTotal,[Discount] = #Discount,[Total_Amount] = #Total_Amount,[Paid_Amount] = #Paid_Amount,[Change_Due] = #Change_Due,[Delivery_Charges] = #Delivery_Charges Where Order_No = '" + Order_No.Text + "' ", con))
{
sc.Parameters.AddWithValue("#Order_No", Order_No.Text);
sc.Parameters.AddWithValue("#Order_Type", Order_Type.Text);
sc.Parameters.AddWithValue("#Order_Date", Order_Date.Text);
sc.Parameters.AddWithValue("#Customer_Name", Customer_Name.Text);
sc.Parameters.AddWithValue("#Contact", Contact.Text);
sc.Parameters.AddWithValue("#Adress", Address.Text);
sc.Parameters.AddWithValue("#Delivery_Address", Delivery_Address.Text);
sc.Parameters.AddWithValue("#Rider", "");
sc.Parameters.AddWithValue("#Items", dgv.Rows[j].Cells[1].Value);
sc.Parameters.AddWithValue("#Price", dgv.Rows[j].Cells[2].Value);
sc.Parameters.AddWithValue("#Qty", dgv.Rows[j].Cells[3].Value);
sc.Parameters.AddWithValue("#Item_Total", dgv.Rows[j].Cells[4].Value);
sc.Parameters.AddWithValue("#Item_Cat", dgv.Rows[j].Cells[5].Value);
sc.Parameters.AddWithValue("#SubTotal", SubTotal.Text);
sc.Parameters.AddWithValue("#Discount", Discount.Text);
sc.Parameters.AddWithValue("#Total_Amount", Total_Amount.Text);
sc.Parameters.AddWithValue("#Paid_Amount", Paid_Amount.Text);
sc.Parameters.AddWithValue("#Change_Due", Change_Due.Text);
sc.Parameters.AddWithValue("#Delivery_Charges", Del_Charges.Text);
sc.ExecuteNonQuery();
}
}
SuccessBox sb = new SuccessBox();
sb.lbl_Change.Text = Change_Due.Text;
sb.label1.Text = "Successfully Updated";
sb.ShowDialog();
con.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
if i add new item and click on update button so this query replaces my all old items with new one.
Suppose i add Samsung S8 so it willl replace my old items to Samsung S8.
And the result is:
Samsung S8 1 $750
Samsung S8 1 $750
Samsung S8 1 $750
Samsung S8 1 $750
Is there any way to do this?
You have to Set The OrderID Parameter in order to Update the desired Item
This will do the Insert, Update, and Delete for you, all via a DataGrid object.
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace InsertUpdateDeleteDemo
{
public partial class frmMain : Form
{
SqlConnection con= new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=true;");
SqlCommand cmd;
SqlDataAdapter adapt;
//ID variable used in Updating and Deleting Record
int ID = 0;
public frmMain()
{
InitializeComponent();
DisplayData();
}
//Insert Data
private void btn_Insert_Click(object sender, EventArgs e)
{
if (txt_Name.Text != "" && txt_State.Text != "")
{
cmd = new SqlCommand("insert into tbl_Record(Name,State) values(#name,#state)", con);
con.Open();
cmd.Parameters.AddWithValue("#name", txt_Name.Text);
cmd.Parameters.AddWithValue("#state", txt_State.Text);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Inserted Successfully");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Provide Details!");
}
}
//Display Data in DataGridView
private void DisplayData()
{
con.Open();
DataTable dt=new DataTable();
adapt=new SqlDataAdapter("select * from tbl_Record",con);
adapt.Fill(dt);
dataGridView1.DataSource = dt;
con.Close();
}
//Clear Data
private void ClearData()
{
txt_Name.Text = "";
txt_State.Text = "";
ID = 0;
}
//dataGridView1 RowHeaderMouseClick Event
private void dataGridView1_RowHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
ID = Convert.ToInt32(dataGridView1.Rows[e.RowIndex].Cells[0].Value.ToString());
txt_Name.Text = dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString();
txt_State.Text = dataGridView1.Rows[e.RowIndex].Cells[2].Value.ToString();
}
//Update Record
private void btn_Update_Click(object sender, EventArgs e)
{
if (txt_Name.Text != "" && txt_State.Text != "")
{
cmd = new SqlCommand("update tbl_Record set Name=#name,State=#state where ID=#id", con);
con.Open();
cmd.Parameters.AddWithValue("#id", ID);
cmd.Parameters.AddWithValue("#name", txt_Name.Text);
cmd.Parameters.AddWithValue("#state", txt_State.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Record Updated Successfully");
con.Close();
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Update");
}
}
//Delete Record
private void btn_Delete_Click(object sender, EventArgs e)
{
if(ID!=0)
{
cmd = new SqlCommand("delete tbl_Record where ID=#id",con);
con.Open();
cmd.Parameters.AddWithValue("#id",ID);
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Record Deleted Successfully!");
DisplayData();
ClearData();
}
else
{
MessageBox.Show("Please Select Record to Delete");
}
}
}
}

Visual C# Datagrid returning all records from database

I want to display a datagrid that will return records based on a query from my search button but whenever I click the search button, it returns all the records from the database.
HTML
<html>
<asp:TextBox ID="ClientCode" runat="server"></asp:TextBox>
<asp:GridView ID="ClientDataGrid" runat="server" Height="111px"
Width="202px" Visible="False"></asp:GridView>
C#
private void rep_bind()
{
connection();
string query = ""select * from client where client_code ='" +
ClientCode.Text + "'";
SqlDataAdapter da = new SqlDataAdapter(query, con);
DataSet ds = new DataSet();
da.Fill(ds);
ClientDataGrid.DataSource = ds;
ClientDataGrid.DataBind();
}
private void InitializeComponent()
{
}
protected void search_Click(object sender, EventArgs e)
{
Label1.Text = "";
connection();
string query = string.Format("select * from client where client_code
='" + ClientCode.Text + "'") ; ;
SqlCommand com = new SqlCommand(query, con);
com.Parameters.Add("#category", SqlDbType.NVarChar, 20).Value =
category.SelectedItem.Text;
SqlDataReader dr;
dr = com.ExecuteReader();
ListItem selectedItem = category.SelectedItem;
if (string.IsNullOrWhiteSpace(ClientCode.Text) &&
string.IsNullOrWhiteSpace(ClientName.Text))
{
ClientDataGrid.Visible = false;
Label1.Visible = true;
Label1.Text = "Please Enter Correct Search Values";
}
else if (dr.HasRows)
{
dr.Read();
rep_bind();
ClientDataGrid.Visible = true;
}
else
{
ClientDataGrid.Visible = false;
}
}
I want to display records that will match the client code on the text box but it always return all the records from the database.
I'm unable to comment on the actual question so I'll ask it here.
You seem to be executing the same query twice. Once to see if it has any rows and the second time to fill the data grid. You can change this so that the query is executed only once.
One way to prevent SQL injection attacks is to use a Stored Procedure instead of directly creating the query using string interpolation. Use a stored procedure and pass your conditions using parameters.
Here's a link that explains how to create one
https://learn.microsoft.com/en-us/sql/relational-databases/stored-procedures/create-a-stored-procedure
How about this version?
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SqlCommand sCommand;
SqlDataAdapter sAdapter;
SqlCommandBuilder sBuilder;
DataSet sDs;
DataTable sTable;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.;Initial Catalog=pubs;Integrated Security=True";
string sql = "SELECT * FROM Stores";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
sCommand = new SqlCommand(sql, connection);
sAdapter = new SqlDataAdapter(sCommand);
sBuilder = new SqlCommandBuilder(sAdapter);
sDs = new DataSet();
sAdapter.Fill(sDs, "Stores");
sTable = sDs.Tables["Stores"];
connection.Close();
dataGridView1.DataSource = sDs.Tables["Stores"];
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
}
private void new_btn_Click(object sender, EventArgs e)
{
dataGridView1.ReadOnly = false;
save_btn.Enabled = true;
new_btn.Enabled = false;
delete_btn.Enabled = false;
}
private void delete_btn_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Do you want to delete this row ?", "Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
dataGridView1.Rows.RemoveAt(dataGridView1.SelectedRows[0].Index);
sAdapter.Update(sTable);
}
}
private void save_btn_Click(object sender, EventArgs e)
{
sAdapter.Update(sTable);
dataGridView1.ReadOnly = true;
save_btn.Enabled = false;
new_btn.Enabled = true;
delete_btn.Enabled = true;
}
}
}

Delete all the data from the gridview

I want to implement a button on a web page which deletes all the data that has been shown on the gridview. Is there any simpler way to delete all data at once with the button?
It's very simple to do. Just iterate over each row in the gridview with and get the primary key value, then using the sql query to delete the record from the database.
The code here can help you. I am using the NorthWind sample database.
void loaddata()
{
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestDatabaseConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand();
connection.Open();
try
{
command = connection.CreateCommand();
command.CommandText = "SELECT * FROM Employees";
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable datatable = new DataTable();
adapter.Fill(datatable);
GridView1.DataSource = datatable;
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
int employee_id;
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["TestDatabaseConnectionString"].ConnectionString);
SqlCommand command = new SqlCommand();
connection.Open();
try
{
command = connection.CreateCommand();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
employee_id = Convert.ToInt32(GridView1.Rows[i].Cells[0].Text);
command.CommandText = "DELETE FROM Employees WHERE EmployeeID = '" + employee_id + "'";
command.ExecuteNonQuery();
}
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
loaddata();
}
You can always just set the DataSource to null.
someGridView.DataSource = null;
someGridView.DataBind();
I can only be as vague as the question and I still don't quite understand why I can't leave comments, but I can leave an answer...
Anyway, we don't know what you're using to access your database or the model backing the GridView.
Let's say for instance you have the following class backing your GridView (the type of data your GridView consists of that you've set the Datasource to):
public class MyData
{
public int ID { get; set; }
public string SomeData { get; set; }
}
In your ASPX you'd have the following:
<asp:GridView ID="GridView" runat="server"></asp:GridView>
<asp:Button ID="DeleteButton" runat="server" OnClick="DeleteButton_Click"/>
And then in your code-behind, you'd do something like this...
protected void DeleteButton_Click(object sender, EventArgs e)
{
var gridViewItemsToDelete = (IEnumerable<MyData>)GridView.DataSource;
foreach (var idToDelete in gridViewItemsToDelete.Select(r=>r.ID))
{
// Delete the item by its ID
// I don't know what you're using to access your database
}
// Save Changes if you didn't in the foreach loop...
}

C# CheckBoxList update in SQL Server

Please inspect my C# code below and let me know where I am going wrong. Here is what I am experiencing:
1.) If I empty the SendReport column in SQL Server and load the page, the second row of the SendReport automatically gets populated with a 1.
2.) I can place a checkmark, click the button and the SendReport values successfully populate in SQL Server. However, if I uncheck any of them and click the button, none of the values change from 1 to 0. Please help!
$<asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList>
<br />
<asp:Button ID="Button1" runat="server" Text="Save Changes" OnClick="Button1_Click" />
<br />
BACKPAGE:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindCheckBoxList();
}
}
// Setting up the ConnectionString
public string GetConnectionString()
{
return System.Configuration.ConfigurationManager.ConnectionStrings["IPdataConnectionString"].ConnectionString;
}
// Binding the CheckBoxList with Data
private void BindCheckBoxList()
{
DataTable dt = new DataTable();
SqlConnection connection = new SqlConnection(GetConnectionString());
try
{
connection.Open();
string sqlStatement = "SELECT Partner, ID, SendReport FROM Rorts";
SqlCommand sqlCmd = new SqlCommand(sqlStatement, connection);
SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd);
sqlDa.Fill(dt);
if (dt.Rows.Count > 0)
{
CheckBoxList1.DataSource = dt;
CheckBoxList1.DataTextField = "Partner"; // the items to be displayed in the list items
CheckBoxList1.DataValueField = "SendReport"; // the id of the items displayed
CheckBoxList1.DataBind();
//Setting the Selected Items in the ChecBoxList based from the value in the database
//to do this, lets iterate to each items in the list
for (int i = 0; i < dt.Rows.Count; i++)
{
if (!string.IsNullOrEmpty(dt.Rows[i]["SendReport"].ToString()))
{
CheckBoxList1.Items[i].Selected = Convert.ToBoolean(dt.Rows[i]["SendReport"]);
}
}
}
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Fetch Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
connection.Close();
}
}
// Creating the Method for Saving the CheckBoxList Selected Items to the database
private void Update(string name, bool SendReport)
{
SqlConnection connection = new SqlConnection(GetConnectionString());
SqlCommand cmd;
string sqlStatement = string.Empty;
try
{
// open the Sql connection
connection.Open();
sqlStatement = "UPDATE Rorts SET SendReport = #SendReport WHERE Partner = #Partner";
cmd = new SqlCommand(sqlStatement, connection);
cmd.Parameters.AddWithValue("#Partner", name);
cmd.Parameters.AddWithValue("#SendReport", SendReport);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert/Update Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
// close the Sql Connection
connection.Close();
}
}
// Calling the Method for Saving the state of CheckBoxList selected items
protected void Button1_Click(object sender, EventArgs e)
{
string PartnerName = string.Empty;
for (int i = 0; i < CheckBoxList1.Items.Count; i++)
{
if (CheckBoxList1.Items[i].Selected)
{
PartnerName = CheckBoxList1.Items[i].Text;
Update(PartnerName, CheckBoxList1.Items[i].Selected);
}
}
//ReBind the List to retain the selected items on postbacks
BindCheckBoxList();
}
It looks like the issue is due to the if block below from the Button1 click event handler. The result is that only the check boxes that are checked have the values persisted to the database.
if (CheckBoxList1.Items[i].Selected)
{
PartnerName = CheckBoxList1.Items[i].Text;
Update(PartnerName, CheckBoxList1.Items[i].Selected);
}
You can just remove the if statement and persist all of the values or add logic to only persist those that have changed.

Categories

Resources