Saving Gridview Data To Database - c#

I am having a Gridview which i want to save in my another table
My Code is
protected void upload_Click(object sender, EventArgs e)
{
string query1 = "INSERT INTO tbl_Pre_Y1_Bus1 (CRITICAL,SPECIFICATION, [1],[2],[3],[4],[5],TMLCAL) VALUES (#CRITICAL, #SPECIFICATION, #[1], #[2], #[3], #[4], #[5], #TMLCAL)";
foreach (GridViewRow row in GridView2.Rows)
{
using (SqlCommand cmd = new SqlCommand(query1))
{
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#CRITICAL", row.Cells[0].ToString());
cmd.Parameters.AddWithValue("#SPECIFICATION", row.Cells[1].ToString());
cmd.Parameters.AddWithValue("#[1]", row.Cells[2].ToString());
cmd.Parameters.AddWithValue("#[2]", row.Cells[3].ToString());
cmd.Parameters.AddWithValue("#[3]", row.Cells[4].ToString());
cmd.Parameters.AddWithValue("#[4]", row.Cells[5].ToString());
cmd.Parameters.AddWithValue("#[5]", row.Cells[6].ToString());
cmd.Parameters.AddWithValue("#TMLCAL",row.Cells[7].ToString());
con.Open(); //here i am having an respected error
cmd.ExecuteNonQuery();
con.Close();
Page.Response.Redirect(Page.Request.Url.ToString(), true);
}
}
}
My error is "Object reference not set to an instance of an object."
help me to resolve this

Replace .ToString() with Convert.ToString as shown below. It will handle blank as well as null value. Then you can check why the value is coming null. You also need to add .Text as shown below.
cmd.Parameters.AddWithValue("#CRITICAL", Convert.ToString(row.Cells[0].Text));
cmd.Parameters.AddWithValue("#SPECIFICATION", Convert.ToString(row.Cells[1].Text));

Before calling .ToString() make sure that your object is not null, Also to read cell text you must put .Text
Something like this :
if (row.Cells[0] != null && !string.IsNullOrEmpty(row.Cells[0].Text)) {
cmd.Parameters.AddWithValue("#CRITICAL", row.Cells[0].Text.ToString());
} else {
// Handle it
}

Related

Why delete command is not executing from c#?

Please check the following code:
protected void Button2_Click(object sender, EventArgs e)
{
string y = foredidel.Text;
try
{
using (var sc = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString))
using (var cmd = sc.CreateCommand())
{
sc.Open();
cmd.CommandText = "DELETE FROM fixap WHERE Id = #word";
cmd.Parameters.AddWithValue("#word", y);
cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
Console.Write("Error");
}
}
When the button is clicked, the specified row should be deleted, but it's not doing anything!
Is there something wrong in my code?
My code was working along with some javascript, so it was like....
onclick give id's value to innerHtml of <asp:Label>.
Then take that value to the variable y in C#(you can check my question for
that variable).
Now as it was runat='server', so I used it to concatenate with my
SqlCommand("#word", y).
I don't know if it was a problem of <asp:Label>, but when I changed it to <asp:TextBox> it worked successfully!
So, answer is just to change <asp:Label> to <asp:TextBox> and according to 1st point change innerHTML to value, and it worked!

Assign a value to drop down list on page_load

I'm trying to assign value to a drop down list on the page_load, but it's not automatically get selected when the page loads up. But when I try to select another value from the drop down list, then the value assigned to it originally gets selected. I think it's something to do with the PostBack, My code is,
if (!string.IsNullOrEmpty(Request.QueryString["selectedReg"]))
{
string selectedReg = Request.QueryString["selectedReg"];
ddlVehicleReg.SelectedIndex = ddlVehicleReg.Items.IndexOf(ddlVehicleReg.Items.FindByText(selectedReg));
}
If I use if(!IsPostBack) still no luck, Any ideas? Thanks a lot in advance
The code block you have written is working. No need to check for postback. Be careful about your querystring. It looks like these pictures for my tests.
After your comment I changed dropdown item list. It is getting data from database. And I called this method in Page_Load
protected void Page_Load(object sender, EventArgs e)
{
FillDropDown();
if (!string.IsNullOrEmpty(Request.QueryString["selectedReg"]))
{
string selectedReg = Request.QueryString["selectedReg"];
ddlVehicleReg.SelectedIndex = ddlVehicleReg.Items.IndexOf(ddlVehicleReg.Items.FindByText(selectedReg));
}
}
protected void FillDropDown()
{
using (SqlConnection con= new SqlConnection("server=.;database=StackTest;integrated security=true") )
{
SqlDataAdapter adp = new SqlDataAdapter("select * from Test", con);
DataTable dt = new DataTable("Test");
adp.Fill(dt);
ddlVehicleReg.DataValueField = "Id";
ddlVehicleReg.DataTextField = "Value";
ddlVehicleReg.DataSource = dt;
ddlVehicleReg.DataBind();
}
}

How to delete row datagrid and update SQL database C#

I am really stuck and non of the books or tread here are user-friendly enough to explain how to delete data from data grid object using C#
from varies of books and fourm threads I have managed to get this coded but it fails to executes the sql command , I have One table call 'SpellingList' and two columns one is ID and the other is Words, all I want to do is delete a row from the datagrid.
Can someone point me to the correct direction , once I solved this , I shall upload some basic easy to follow tutorial so the rest of the newbie can follow this example.
I have used this thread How to delete a selected DataGridViewRow and update a connected database table?
and MCSD Certificaiton Toolkit Exam 70-483 book Page 392 , all attempts have failed.
there is a catch 22 here if I comment out if(dataGridView1.SelectedRows.Count > 0) line , I get the index out of range error .
private void btnDelete_Click(object sender, EventArgs e)
{
// My SQL connectionString
SqlConnection myConnection = new SqlConnection("Data Source=Epic-LaptopWR;Initial Catalog=words;Integrated Security=True");
myConnection.Open();
foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
{
if(dataGridView1.SelectedRows.Count > 0)
{
int selectedIndex = dataGridView1.SelectedRows[0].Index;
// gets the RowID from the first column in the grid
int rowID = int.Parse(dataGridView1[0, selectedIndex].Value.ToString());
// your code for deleting it from the database
string sql = "DELETE FROM SpellingList WHERE Words =" + selectedIndex;
SqlCommand deleteRecord = new SqlCommand();
deleteRecord.Connection = myConnection;
deleteRecord.CommandType = CommandType.Text;
deleteRecord.CommandText = sql;
SqlParameter RowParameter = new SqlParameter();
RowParameter.ParameterName = "#Words";
RowParameter.SqlDbType = SqlDbType.Int;
RowParameter.IsNullable = false;
RowParameter.Value = rowID;
deleteRecord.Parameters.Add(RowParameter);
deleteRecord.Connection.Open();
deleteRecord.ExecuteNonQuery();
if (oneCell.Selected)
dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
deleteRecord.Connection.Close();
wordsDataSet.GetChanges();
// booksDataset1.GetChanges();
spellingListTableAdapter.Fill(wordsDataSet.SpellingList);
}// end of if
// then your code for refreshing the DataGridView
}// end of for each statement
myConnection.Close();
}// end of delete Button
We could simplify a lot. And fix some evident bugs.
The ID field is the key field of your table and thus you should use it to find the row to delete, then, a parameter, to be useful, needs a parameter placeholder in the command text that you want to execute
private void btnDelete_Click(object sender, EventArgs e)
{
// No row selected no delete....
if(dataGridView1.SelectedRows.Count == 0)
return; // show a message here to inform
// Prepare the command text with the parameter placeholder
string sql = "DELETE FROM SpellingList WHERE ID = #rowID";
// Create the connection and the command inside a using block
using(SqlConnection myConnection = new SqlConnection("...."))
using(SqlCommand deleteRecord = new SqlCommand(sql, myConnection))
{
myConnection.Open();
int selectedIndex = dataGridView1.SelectedRows[0].Index;
// gets the RowID from the first column in the grid
int rowID = Convert.ToInt32(dataGridView1[0, selectedIndex].Value);
// Add the parameter to the command collection
deleteRecord.Parameters.Add("#rowID", SqlDbType.Int).Value = rowID;
deleteRecord.ExecuteNonQuery();
// Remove the row from the grid
dataGridView1.Rows.RemoveAt(selectedIndex);
}
}
As you can see, connections and commands are disposable objects and should be enclosed in a using statement to ensure proper closing and disposing also in case of exceptions.
Finally, removing the row from the grid should be done simply using the index of the row, removing the line in a single command. You don't need to loop over the cells to delete them one by one.
I would humbly like to thank Steve for his contribution , without guru's like him us newbies would have spent hours to end in trying to solve a simple yet complex problem.
Here is the working code with few modification that by passes the index out of bound error:
private void btnDelete_Click(object sender, EventArgs e)
{
// No row selected no delete....
if(dataGridView1.SelectedRows.Count == 0)
{
MessageBox.Show("No row selected !");// show a message here to inform
}
// Prepare the command text with the parameter placeholder
string sql = "DELETE FROM SpellingList WHERE ID = #rowID";
// Create the connection and the command inside a using block
using(SqlConnection myConnection = new SqlConnection("Data Source=Epic-LaptopWR;Initial Catalog=words;Integrated Security=True"))
using (SqlCommand deleteRecord = new SqlCommand(sql, myConnection))
{
myConnection.Open();
MessageBox.Show("The SQL Connection is Open");
// this overcomes the out of bound error message
// if the selectedRow is greater than 0 then exectute the code below.
if(dataGridView1.CurrentCell.RowIndex > 0)
{
int selectedIndex = dataGridView1.SelectedRows[0].Index;
// gets the RowID from the first column in the grid
int rowID = Convert.ToInt32(dataGridView1[0, selectedIndex].Value);
// Add the parameter to the command collection
deleteRecord.Parameters.Add("#rowID", SqlDbType.Int).Value = rowID;
deleteRecord.ExecuteNonQuery();
// Remove the row from the grid
dataGridView1.Rows.RemoveAt(selectedIndex);
}
}
}// end of delete Button
Please ensure that your datagrid property for SelectionMode is set to 'FullRowSelect' this as mention by Steve will populated with selected rows.
In additional to the above this is for the newbies , please ensure you have a Primary key set as ID with integer values ,in my first error I did not have any data in the primary key it was NULL with one field { Colum called Words} .
Within a week or so I shall post a step by step guide on how to create a simple database watch out for this space.

ASPxGridView and LinqServerModeDataSource: Inserting and updating rows without showing all columns in grid

How do I use a LinqServerModeDataSource to insert or edit rows of the underlying data table when I do not show all fields of that table in the ASPxGridView?
Similar questions have been asked, but this is not a duplicate. For example, this one asks about a LinqServerModeDataSource and the accepted answer tells how to use an ordinary SqlDataSource.
I have an ASPxGridView hooked up to a table via a LinqServerModeDataSource. But I do not show all columns in the grid. For example, there are columns for the date created and some others that the user doesn't need to know about. I am allowing inline editing in the grid, but in the Inserting or Updating event, the new values passed are just a dictionary of the values displayed in the grid.
What about the other values? I would expect to be able to set any of the values for the underlying data row programmatically in the event handler, regardless of whether they are displayed and thus edited by the user. How do I get access to them and set the other values in the events of the LinqServerModeDataSource? I am having no luck reading the devexpress documentation.
I'm guessing that there must be a Linq class that hooks into the table that I can use in those events, similarly to the Selecting event. But how?
Here's what the Selecting event handler looks like... Is there not some similar interface I can use to access the underlying data in the other events?
protected void dsRecipients_Selecting(object sender, DevExpress.Data.Linq.LinqServerModeDataSourceSelectEventArgs e)
{
SmsRecipientsDataContext context = new SmsRecipientsDataContext();
IQueryable<NotificationParty> val = context.NotificationParties;
int notificationGroupID = Convert.ToInt32(Context.Session["NotificationGroupID"]);
val = val.Where(n => n.NotificationGroupID == notificationGroupID && n.Active);
e.KeyExpression = "ID";
e.QueryableSource = val;
}
As much as I hate answering my own question...
I can't figure out how to get this control to do what I want. However, a simple workaround is to handle the insert and update on the grid itself.
So, it's working now. I set the EnableUpdate and EnableInsert properties on the LinqServerModeDataSource to false, and simply handle the grid's RowInserting and RowUpdating events, where I go directly to the database.
For example, my inserting event handler is this:
protected void recipientsGrid_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
{
using (SqlConnection connection = new SqlConnection(App_Logic.Wrappers.DatabaseConnectionString()))
{
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.Transaction = connection.BeginTransaction();
try
{
command.CommandText = " INSERT INTO NotificationParty(NotificationGroupID, FirstName, LastName, CellNumber, Active, UserCreated, DateCreated) VALUES " +
"(#NotificationGroupID, #FirstName, #LastName, #CellNumber, #Active, #UserCreated, GETDATE())";
command.Parameters.AddWithValue("#NotificationGroupID", Convert.ToInt32(Context.Session["NotificationGroupID"]));
command.Parameters.AddWithValue("#FirstName", e.NewValues["FirstName"]);
command.Parameters.AddWithValue("#LastName", e.NewValues["LastName"]);
command.Parameters.AddWithValue("#CellNumber", e.NewValues["CellNumber"]);
command.Parameters.AddWithValue("#Active", 1);
command.Parameters.AddWithValue("#UserCreated", Session["UID"]);
command.ExecuteNonQuery();
command.Transaction.Commit();
}
catch
{
command.Transaction.Rollback();
}
}
}
recipientsGrid.CancelEdit();
e.Cancel = true;
}
And my updating event handler is this:
protected void recipientsGrid_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
{
using (SqlConnection connection = new SqlConnection(App_Logic.Wrappers.DatabaseConnectionString()))
{
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.Transaction = connection.BeginTransaction();
try
{
command.CommandText = " UPDATE NotificationParty SET FirstName = #FirstName, LastName = #LastName, CellNumber = #CellNumber, UserModified = #UserModified, DateModified = GETDATE() WHERE ID = #ID";
command.Parameters.AddWithValue("#ID", e.Keys[0]);
command.Parameters.AddWithValue("#FirstName", e.NewValues["FirstName"]);
command.Parameters.AddWithValue("#LastName", e.NewValues["LastName"]);
command.Parameters.AddWithValue("#CellNumber", e.NewValues["CellNumber"]);
command.Parameters.AddWithValue("#UserModified", Session["UID"]);
command.ExecuteNonQuery();
command.Transaction.Commit();
}
catch
{
command.Transaction.Rollback();
}
}
}
recipientsGrid.CancelEdit();
e.Cancel = true;
}

Displaying Database Information in TextBox From Another Form Using DataGridView

I am trying to display information (User Comment) from my MySQL database into a textbox in another form. I am using a datagridview to select the UID to identify which user the comment is for. My code is in the load event of the Comment form, like so...
try
{
// Check if a row is selected.
string cRow = admin.gridClients.CurrentRow.Cells[0].Value.ToString();
string Query = "SELECT Admin_Com FROM cpr_clients WHERE Client_ID='" + cRow + "';";
MySqlConnection myConn = new MySqlConnection(strConnect);
MySqlCommand myCmd = new MySqlCommand(Query, myConn);
MySqlDataReader myReader;
myConn.Open();
myReader = myCmd.ExecuteReader();
while (myReader.Read())
{
txtAdminCom.Text = myReader["Admin_Com"].ToString();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Edit: I have updated my code. The code only retrieves the comment of the first row in the datagridview even if I have selected another row.
Likely your problem is there is no CurrentRow on your source (admin.gridClients) grid view. This will cause attempting to access .Cells to throw the error you are getting because CurrentRow == null.
Since you only need this value to identify the Id in the frmAdminComment, read the value in your source form and then pass it the constructor of frmAdminComment:
private string _id;
public frmAdminComment(string id)
{
// Initialization code you already have.
// Set the Id for this instance.
_id = id;
}
Now reference the _id variable in your load method:
string Query = "SELECT Admin_Com FROM cpr_clients WHERE Client_ID='" + _id + "';";
This puts the burden of checking for a valid value in the admin object which is creating frmAdminComment.
// In the "admin" object.
if (gridClients.CurrentRow == null)
{
MessageBox.Show("No CurrentRow is set in the source grid.");
return;
}
else
{
// CurrentRow is set - safe to reference it.
var adminComment = new frmAdminComment(gridClients.CurrentRow.Cells[0].Value.ToString());
adminComment.Show();
}
You may want to consider using the SelectedRows property instead. It would work like this:
// Check if a row is selected.
// In the "admin" object.
if (gridClients.SelectedRows.Length == 0)
{
MessageBox.Show("No rows selected in the source grid.");
}
else
{
// CurrentRow is set - safe to reference it.
var adminComment = new frmAdminComment(gridClients.SelectedRows[0].Cells[0].Value.ToString());
adminComment.Show();
}
Note that if you use SelectedRows then you may want to set the properties on gridClients to allow only a single row to be selected at one time with the selection mode set to FullRowSelect.

Categories