how to store gridview contents into database table - c#

I Have a gridview with just one column. I have written code like
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
SqlConnection con = new SqlConnection(strConnString);
con.Open();
for (int i = 0; i < GridView1.Rows.Count; i++)
{
string Users = GridView1.Rows[i].Cells[0].Text;
string strQuery = "insert into Table1 (FileName, DateTimeUploaded, Type, Username)" +
" values(#FileName, #DateTimeUploaded, #Type, #Username)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#FileName", datalink);
cmd.Parameters.AddWithValue("#Type", ext);
cmd.Parameters.AddWithValue("#DateTimeUploaded", DateTime.Now);
cmd.Parameters.AddWithValue("#Username", Users);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.ExecuteNonQuery();
}
con.Close();
con.Dispose();
}
If this gridview has 2 rows, then the first row is stored in database twice. If gridview has 3 rows then the first row is stored thrice. How can I solve this?

Explanation:
You are inserting your data into the database inside your GridView's RowDataBound event - this is executing every time a DataRow is being bound! This, along with the fact that you're looping accross every row each time using:
for (int i = 0; i < GridView1.Rows.Count; i++) { // inserting record from each row }
means your rows are going to be inserted more than once as more rows are bound. You need to remove your for loop, and use e.Row.Cells[0] instead to reference and insert just the currently bound row data.
string Users = e.Row.Cells[0].Text;
You probably also want to check for only DataRows so your operations don't occur on footer/header rows etc.
New Code:
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
SqlConnection con = new SqlConnection(strConnString);
con.Open();
string Users = e.Row.Cells[0].Text; // current row being bound
string strQuery = "insert into Table1 (FileName, DateTimeUploaded, Type, Username)" +
" values(#FileName, #DateTimeUploaded, #Type, #Username)";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.AddWithValue("#FileName", datalink);
cmd.Parameters.AddWithValue("#Type", ext);
cmd.Parameters.AddWithValue("#DateTimeUploaded", DateTime.Now);
cmd.Parameters.AddWithValue("#Username", Users);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
cmd.ExecuteNonQuery();
con.Close();
con.Dispose();
}
}

Related

How to delete a data in database table

I have this form that takes these information from user #ID, #From, #To, #Title, #Message. Then it insert them into a database table.
How can I delete a certain data using the #ID? User will have a dataGridView1 with all the datatable, then by getting the CurrentCell it will delete this certain data.
private void delet_button_Click(object sender, EventArgs e)
{
int i = dataGridView1.CurrentCell.RowIndex;
string strid = dataGridView1[0, i].Value.ToString();
//MessageBox.Show(strid);
int id = Convert.ToInt32(strid);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Delete * from MessagesTable where [ID]=#ID ";
cmd.Parameters.AddWithValue("#ID", id);
MessageBox.Show("Message was deleted");
BindGrid();
}
You are almost certainly going about this all wrong. You should start with a DataTable. If appropriate, you can query the database to populate it by calling Fill on a data adapter. You can then bind the table to your DataGridView via a BindingSource, which you would add in the designer, e.g.
var table = new DataTable();
using (var adapter = new SqlDataAdapter("SQL query here", "connection string here"))
{
adapter.Fill(table);
}
BindingSource1.DataSource = table;
DataGridView1.DataSource = BindingSource1;
You then mark the current row as deleted by calling RemoveCurrent on the BindingSource. That will hide the row in the grid but it won't affect the database at that stage. To save the changes to the database, you call Update on an appropriately configured data adapter, which may be the same one you called Fill on in the first place. You could call Update to save the change as soon as the user deletes the row or you could just cache all changes locally - inserts, updates and deletes - and then call Update once at the end to save all the changes together.
Add cmd.ExecuteNonQuery();
private void delet_button_Click(object sender, EventArgs e)
{
int i = dataGridView1.CurrentCell.RowIndex;
string strid = dataGridView1[0, i].Value.ToString();
//MessageBox.Show(strid);
int id = Convert.ToInt32(strid);
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Delete from MessagesTable where [ID]=#ID ";
cmd.Parameters.AddWithValue("#ID", id);
cmd.ExecuteNonQuery();
MessageBox.Show("Message was deleted");
BindGrid();
}

C# Show list in combobox based on selection in first combobox

Good day.
I just looking for a solution to my problem. I just trying to make my first program and I have encountered this problem. I have 2 comboboxes, the first one is the list of supplier and the second one is the list of items. Now I need to filter down what will show in the 2nd combobox based on the 1st combobox, but still in the 2nd combobox. It always shows all the item that is listed from my database. All data are coming from SQL Database and below is the code that I am working with:
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tblmaster where Supplier = '" + comboBox3.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
foreach(DataRow dr in dt.Rows) {
comboBox5.Items.Add(dr["ProductCode"].ToString());
}
conn.Close();
}
Try to clear the items before the loop.
private void comboBox3_SelectedIndexChanged(object sender, EventArgs e)
{
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from tblmaster where Supplier = '" + comboBox3.SelectedItem.ToString() + "'";
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
SqlDataAdapter Da = new SqlDataAdapter(cmd);
Da.Fill(dt);
comboBox5.Items.Clear();
foreach(DataRow dr in dt.Rows) {
comboBox5.Items.Add(dr["ProductCode"].ToString());
}
conn.Close();
}

How to insert value from gridview into database

I have two tables in a SQL Server database. I select from table ADMS and I need to insert master table by gridview but I dont know how to insert with gridview. Please help. I've tried for many days and I did not pass yet
protected void Button3_Click1(object sender, EventArgs e)
{
if (RadioButton2.Checked)
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ADMS_Machining where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
else
{
SqlConnection con = new SqlConnection(MyConnectionString);
// con.Open(); // don't need the Open, the Fill will open and close the connection automatically
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM Machining_Master where datetime='" + TextBox1.Text + "'", con);
mytable = new DataTable();
da.Fill(mytable);
GridView2.DataSource = mytable;
GridView2.DataBind();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
SqlCommand cmd = new SqlCommand();
String strConnString, strSQL;
strConnString = "Server=kane-pc;UID=sa;PASSWORD=1234;Database=Machining;Max Pool Size=400;Connect Timeout=600;";
//here
conn.ConnectionString = conn;
conn.Open();
cmd.Connection = conn;
cmd.CommandText = strSQL;
}
You can extract values from a grid view depending on what you have placed in the cells...
string value = this.GridView2.Rows[0].Cells[0].Text;
You can also track the selected row event, and get specific controls like the following...
protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
string someValueTakenFromLabel = (GridView2.SelectedRow.FindControl("lblAnyLabelHere") as Label).Text;
// .... do something with value here
}
I suggest you go through some tutorials though to get the hang of how to use GridView.
http://www.asp.net/web-forms/videos/building-20-applications/lesson-8-working-with-the-gridview-and-formview
http://www.aspsnippets.com/Articles/How-to-get-Selected-Row-cell-value-from-GridView-in-ASPNet.aspx
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview%28v=vs.110%29.aspx
You have to first read data from cells and then insert them into database using SqlCommand.
Assuming that you have M_ID and M_NAME columns in your Machining_Master table you can insert values to database as below:
//Assuming that your id column is first column and name is second column
//get value of id and name
int mId = Convert.ToInt32(GridView2.SelectedRow.Cells[0].Text);
string mName = GridView2.SelectedRow.Cells[1].Text;
string connectionStrng = "your connection string";
string insertSql = "INSERT INTO Machining_Master (M_ID, M_NAME) VALUES (#mId, #mName)";
using (SqlConnection conn = new SqlConnection(connectionStrng))
{
using (SqlCommand cmd = new SqlCommand(insertSql, conn))
{
try
{
cmd.Parameters.Add(new SqlParameter("mId", mId));
cmd.Parameters.Add(new SqlParameter("mName", mName));
conn.Open();
cmd.ExecuteNonQuery();
}
finally
{
//Close connection
conn.Close();
}
}
}

Insert data from a GridView into database on a click of a Button

I am trying to insert every row in the GridView into a table on a click of button. My problem with the code below is that it is only inserting the first row and repeating the same record in the rest of the gridview. For example, if i have on the first row:
2 ABC ATL
it will repeat this for the rest of the columns. How can i capture every row and insert it into my database? thanks.
Here is my code:
protected void Insert(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Label ID = GridView1.Rows[0].FindControl("lblID") as Label;
Label NAME = GridView1.Rows[0].FindControl("lblQue") as Label;
TextBox LOC = GridView1.Rows[0].FindControl("txtPM") as TextBox;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText =
"insert into myTable(ID, NAME, LOC ) values(#ID, #NAME, #LOC) " +
// "where ID=#ID;" +
"SELECT ID, NAME, LOC FROM MYTABLE";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ID.Text;
cmd.Parameters.Add("#NAME", SqlDbType.VarChar).Value = NAME.Text;
cmd.Parameters.Add("#LOC", SqlDbType.VarChar).Value = LOC.Text;
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
}
}
Problem : you have hardcoded index zero using following statement:
GridView1.Rows[0]
it will always insert first record from GridView
Solution : increment row count for each row.
Try This:
protected void Insert(object sender, EventArgs e)
{
int index=0;
foreach (GridViewRow row in GridView1.Rows)
{
if (row.RowType == DataControlRowType.DataRow)
{
Label ID = GridView1.Rows[index].FindControl("lblID") as Label;
Label NAME = GridView1.Rows[index].FindControl("lblQue") as Label;
TextBox LOC = GridView1.Rows[index].FindControl("txtPM") as TextBox;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into myTable(ID, NAME, LOC ) values(#ID, #NAME, #LOC) " +
// "where ID=#ID;" +
"SELECT ID, NAME, LOC FROM MYTABLE";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ID.Text;
cmd.Parameters.Add("#NAME", SqlDbType.VarChar).Value = NAME.Text;
cmd.Parameters.Add("#LOC", SqlDbType.VarChar).Value = LOC.Text;
GridView1.EditIndex = -1;
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
}
index++;
}
}
GridView.Rows[0] will take first row for all the rows.
Instead of that use row from your foreach declaration.
Replace
Label ID = GridView1.Rows[0].FindControl("lblID") as Label;
With
Label ID = row.FindControl("lblID") as Label;
please use this code
row.FindControl("lblID") as Label; instead of GridView1.Rows[0].FindControl("lblID") as Label;
and also first execute your insert query then call your select query
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into myTable(ID, NAME, LOC ) values(#ID, #NAME, #LOC) ";
cmd.Parameters.Add("#ID", SqlDbType.VarChar).Value = ID.Text;
cmd.Parameters.Add("#NAME", SqlDbType.VarChar).Value = NAME.Text;
cmd.Parameters.Add("#LOC", SqlDbType.VarChar).Value = LOC.Text;
cmd.ExcutrNonQuery();
cmd.CommandText = "SELECT ID, NAME, LOC FROM MYTABLE";
.... //next binding code

Using a literal to display results from query

I'm trying to display multiple rows from a query into a literal in asp.net c#. Here is my code for doing so:
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["RaiseFantasyLeagueConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("[dbo].[GetUsersLeagues]", conn);
cmd.CommandType = CommandType.StoredProcedure;
string userId = Membership.GetUser().ProviderUserKey.ToString();
SqlParameter userIDParam = new SqlParameter("#userId", userId);
cmd.Parameters.Add(userIDParam);
conn.Open();
SqlDataReader dReader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (dReader.Read())
{
usersLeagues.Text = (dReader["LeagueName"].ToString());
}
dReader.Close();
conn.Close();
}
My issue is that the literal is only displaying one of the rows, i've tried this with a list box and all rows were displayed.
Any suggestions?
Thanks in advance!
You are replacing the value of the Text property on each iteration:
while (dReader.Read())
{
usersLeagues.Text = (dReader["LeagueName"].ToString());
}
Instead of that, you need to concatenate the values on each iteration:
while (dReader.Read())
{
usersLeagues.Text += (dReader["LeagueName"].ToString()) + Environment.NewLine;
}
In the above example, using += causes an append to the current value of usersLeagues.Text, instead of a replacement.

Categories

Resources