Need Id to Upload excel sheet in the gridview - c#

I have a feature to upload the Excel sheet data into the gridview. The data will get inserted into the child table of database.
Now, My issue here is. One of the column has a relation with the Master table.
So, untill and unless I add that column ID which has a relation it gives me error as
The Student_id column was not supplied
Here is my code
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select count(email) from tbl_student_report where email=#email", con);
cmd.Parameters.Add("#email", SqlDbType.VarChar).Value = dt.Rows[i]["Email Id"].ToString();
int count = (int)cmd.ExecuteScalar();
if (count > 0)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Duplicate user in the sheet, Sheet will not be uploaded..!!!');window.location ='csrstudentprogress.aspx';", true);
continue;
}
cmd = new SqlCommand("INSERT INTO tbl_student_report(NgoId,student_id,name,email,class,attendance,english_subject_marks,math_subject_marks,academic_performance,extra_activities,social_skills,general_health,date_of_record,modified_date,status,active) VALUES(#NgoId,#student_id,#name,#email,#class,#attendance,#english_subject_marks,#math_subject_marks,#academic_performance,#extra_activities,#social_skills,#general_health,#date_of_record,#modified_date,#status,#active)", con);
cmd.Parameters.Add("#NgoId", SqlDbType.Int).Value = dt.Rows[i]["NgoId"].ToString();
cmd.Parameters.Add("#student_id", SqlDbType.Int).Value = dt.Rows[i]["StudentId"].ToString();
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = dt.Rows[i]["Name"].ToString();
cmd.Parameters.Add("#email", SqlDbType.NVarChar).Value = dt.Rows[i]["Email Id"].ToString();
cmd.Parameters.Add("#class", SqlDbType.VarChar).Value = dt.Rows[i]["Class"].ToString();
cmd.Parameters.Add("#attendance", SqlDbType.Decimal).Value = dt.Rows[i]["Attendance"].ToString();
cmd.Parameters.Add("#english_subject_marks", SqlDbType.Int).Value = dt.Rows[i]["English Subject Marks"].ToString();
cmd.Parameters.Add("#math_subject_marks", SqlDbType.Int).Value = dt.Rows[i]["Maths Subject Marks"].ToString();
cmd.Parameters.Add("#academic_performance", SqlDbType.NVarChar).Value = dt.Rows[i]["Academic Performance"].ToString();
cmd.Parameters.Add("#extra_activities", SqlDbType.NVarChar).Value = dt.Rows[i]["Extra Activities"].ToString();
cmd.Parameters.Add("#social_skills", SqlDbType.NVarChar).Value = dt.Rows[i]["Social Skills"].ToString();
cmd.Parameters.Add("#general_health", SqlDbType.NVarChar).Value = dt.Rows[i]["General Health"].ToString();
cmd.Parameters.Add("#status", SqlDbType.Bit).Value = dt.Rows[i]["Status"].ToString();
cmd.Parameters.Add("#date_of_record", SqlDbType.DateTime).Value = dt.Rows[i]["Date Of Record"].ToString();
cmd.Parameters.Add("#modified_date", SqlDbType.DateTime).Value = dt.Rows[i]["Modified Date"].ToString();
cmd.Parameters.Add("#active", SqlDbType.Bit).Value = dt.Rows[i]["Active"].ToString();
cmd.ExecuteNonQuery();
con.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Sheet uploaded successfully');window.location ='csrstudentprogress.aspx';", true);
}
Please suggest what to do in this case, because User will not add student_id in the excel sheet and upload.
I am using sql-server 2008
How to achieve this ??

I got it done by trying myself like below:-
Helper class
public static DataTable GetUserIdByName(string userName,string userType)
{
string conString = ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(conString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM tbl_User WHERE Username=#Username AND UserType=#UserType", con);
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = userName;
cmd.Parameters.Add("#UserType", SqlDbType.VarChar).Value = userType;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);
return dt;
}
}
And calling the Class in the Export function did the job:-
DataTable table = GeneralHelper.GetUserIdByName(Session["User"].ToString(), Session["UserType"].ToString());
for (int i = 0; i < dt.Rows.Count; i++)
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
con.Open();
if (table != null && table.Rows.Count > 0)
{
string StudentId = GetNgoIdStudentId(dt.Rows[i]["Email Id"].ToString());
if (StudentId != null)
{
SqlCommand cmd = new SqlCommand("INSERT INTO tbl_student_report(student_id,name,emailid,class,attendance,english_subject_marks,math_subject_marks,academic_performance,extra_activities,social_skills,general_health,date_of_record,modified_date,status,active) VALUES(#student_id,#name,#emailid,#class,#attendance,#english_subject_marks,#math_subject_marks,#academic_performance,#extra_activities,#social_skills,#general_health,#date_of_record,#modified_date,#status,#active)", con);
cmd.Parameters.Add("#NgoId", SqlDbType.Int).Value = table.Rows[0]["NgoId"].ToString();
cmd.Parameters.Add("#student_id", SqlDbType.Int).Value = StudentId;
cmd.Parameters.Add("#name", SqlDbType.VarChar).Value = dt.Rows[i]["Name"].ToString();
cmd.Parameters.Add("#emailid", SqlDbType.NVarChar).Value = dt.Rows[i]["Email Id"].ToString();
cmd.Parameters.Add("#class", SqlDbType.VarChar).Value = dt.Rows[i]["Class"].ToString();
cmd.Parameters.Add("#attendance", SqlDbType.Decimal).Value = dt.Rows[i]["Attendance"].ToString();
cmd.Parameters.Add("#english_subject_marks", SqlDbType.Int).Value = dt.Rows[i]["English Subject Marks"].ToString();
cmd.Parameters.Add("#math_subject_marks", SqlDbType.Int).Value = dt.Rows[i]["Maths Subject Marks"].ToString();
cmd.Parameters.Add("#academic_performance", SqlDbType.NVarChar).Value = dt.Rows[i]["Academic Performance"].ToString();
cmd.Parameters.Add("#extra_activities", SqlDbType.NVarChar).Value = dt.Rows[i]["Extra Activities"].ToString();
cmd.Parameters.Add("#social_skills", SqlDbType.NVarChar).Value = dt.Rows[i]["Social Skills"].ToString();
cmd.Parameters.Add("#general_health", SqlDbType.NVarChar).Value = dt.Rows[i]["General Health"].ToString();
cmd.Parameters.Add("#status", SqlDbType.Bit).Value = dt.Rows[i]["Status"].ToString();
if (string.IsNullOrEmpty(dt.Rows[i]["Date Of Record"].ToString()))
{
cmd.Parameters.Add("#date_of_record", SqlDbType.DateTime).Value = DateTime.Now;
}
else
{
cmd.Parameters.Add("#date_of_record", SqlDbType.DateTime).Value = dt.Rows[i]["Date Of Record"].ToString();
}
if (string.IsNullOrEmpty(dt.Rows[i]["Modified Date"].ToString()))
{
cmd.Parameters.Add("#modified_date", SqlDbType.DateTime).Value = DateTime.Now;
}
else
{
cmd.Parameters.Add("#modified_date", SqlDbType.DateTime).Value = dt.Rows[i]["Modified Date"].ToString();
}
cmd.Parameters.Add("#active", SqlDbType.Bit).Value = dt.Rows[i]["Active"].ToString();
cmd.ExecuteNonQuery();
con.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Sheet uploaded successfully');window.location ='csrstudentprogress.aspx';", true);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Student not found');", true);
}
}
else
{
//Error
}
}
}

Related

How do i update picture using sqlconnection

it always show an error Incorrect syntax near ')'.
I didnt see any wrong inputs
See my code below
byte[] content = ImageToStream(fName);
cnn.Open();
string sql = "update tblbarangayofficials set pic=#pic,fname=#fname,mname=#mname,lname=#lname,position=#position,startterm=#startterm,endterm=#endterm where id=#id)";
SqlCommand cmd1 = new SqlCommand(sql, cnn);
cmd1.Parameters.AddWithValue("#pic", SqlDbType.Image).Value = content;
cmd1.Parameters.AddWithValue("#fname", SqlDbType.VarChar).Value = txtfirstname.Text;
cmd1.Parameters.AddWithValue("#mname", SqlDbType.VarChar).Value = textBox1.Text;
cmd1.Parameters.AddWithValue("#lname", SqlDbType.VarChar).Value = txtlastname.Text;
cmd1.Parameters.AddWithValue("#position", SqlDbType.VarChar).Value = comboBox2.Text;
cmd1.Parameters.AddWithValue("#startterm", SqlDbType.DateTime).Value = dateTimePicker2.Value.Date;
cmd1.Parameters.AddWithValue("#endterm", SqlDbType.DateTime).Value = dateTimePicker1.Value.Date;
cmd1.Parameters.AddWithValue("#id", SqlDbType.Int).Value = int.Parse(ID.Text);
cmd1.ExecuteNonQuery();
cnn.Close();
MessageBox.Show("successfully updated");
dataGridView1.DataSource = db.sp_viewofficials();
it should save to sql server my save works
Your update statement has extra ending bracket which is not needed.
"update tblbarangayofficials set pic=#pic,fname=#fname,mname=#mname,lname=#lname,position=#position,startterm=#startterm,endterm=#endterm where id=#id"

FileUpload with its updation status

I want to make a functionality where a User will upload the file and its name and description will be shown in the gridview.
Now here what I want is, if the same file has some changes, it needs to be uploaded again and the since its uploaded for the second time. I will be having one more column as FileRevision which will show the no of times files has been updated.
See the image for your reference:-
Do let me know from where to start.
I got it done by myself, like below:-
FileUpload Control in ASPX page
<asp:FileUpload ID="fupreportfile" runat="server" CssClass="form-control" ValidationGroup="AddNew" />
Now, on button click it will check whether the file Exist or not. Checking thorugh CS code:-
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString);
using (SqlCommand cmd = conn.CreateCommand())
{
if (fupreportfile.HasFiles)
{
int count = CheckFileExists(fupreportfile.PostedFile.FileName);
fupreportfile.SaveAs(Server.MapPath("~/ReportFolder/" + fupreportfile.PostedFile.FileName));
if (count > 0)
{
cmd.CommandText = " Update tbl_reports SET revision=#revision Where Id=#Id";
cmd.Parameters.AddWithValue("#Id", GetIdByFileName(fupreportfile.PostedFile.FileName));
cmd.Parameters.Add("#revision", SqlDbType.VarChar).Value = (count + 1).ToString();
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Reports updated sucessfully');window.location ='csrreports.aspx';", true);
}
else
{
conn.Open();
SqlCommand cmd1 = new SqlCommand("Insert into tbl_reports (NgoId,report_type_id,report_title,report_file,report_desc,revision) values(#NgoId, #report_type_id, #report_title,#report_file,#report_desc,#revision)", conn);
cmd1.Parameters.Add("#NgoId", SqlDbType.Int).Value = ddlNgoName.SelectedValue;
cmd1.Parameters.Add("#report_type_id", SqlDbType.Int).Value = ddlReportType.SelectedValue;
cmd1.Parameters.Add("#report_title", SqlDbType.NVarChar).Value = txtreporttitle.Text;
cmd1.Parameters.Add("#report_file", SqlDbType.VarChar).Value = fupreportfile.PostedFile.FileName;
cmd1.Parameters.Add("#report_desc", SqlDbType.NVarChar).Value = txtreportdescription.Text;
cmd1.Parameters.Add("#revision", SqlDbType.VarChar).Value = (count + 1).ToString();
cmd1.ExecuteNonQuery();
conn.Close();
ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('Reports added sucessfully');window.location ='csrreports.aspx';", true);
}
}
}
}
Code for checking file :-
public int CheckFileExists(string fileName)
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM tbl_reports WHERE report_file=#report_file", con);
cmd.Parameters.Add("#report_file", SqlDbType.VarChar).Value = fileName;
con.Open();
int count = (int)cmd.ExecuteScalar();
return count;
}
}
Also, I need to check the ID for which Row it is updating. So the code for that is
public int GetIdByFileName(string fileName)
{
using (SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultCSRConnection"].ConnectionString))
{
SqlCommand cmd = new SqlCommand("SELECT Id FROM tbl_reports WHERE report_file=#report_file", con);
cmd.Parameters.Add("#report_file", SqlDbType.VarChar).Value = fileName;
con.Open();
int count = (int)cmd.ExecuteScalar();
return count;
}
}
I checked this and it worked for me :)

Must declare the scalar variable "#username". How to overcome it

I am having problem with my code Always having the error which i am not understanding. Please help with my code
i want to retrieve the user details from the db for login page
string uname = TextBox1.Text.Trim();
string pass = TextBox2.Text.Trim();
try
{
con.Open();
string query = "SELECT user_name, user_password FROM [user] where user_name=#username and user_password=#password";
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = uname;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = pass;
cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
rd = cmd.ExecuteReader();
if (rd.HasRows)
{
Response.Write("Login successful");
}
else
{
Response.Write("login Unsucessful");
}
}
catch (Exception)
{
throw;
}
finally
{
con.Close();
}
}
You need to create your cmd prior to adding the paramaters. Your code should look like:
con.Open();
string query = "SELECT user_name, user_password FROM [user] where user_name=#username and user_password=#password";
cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#username", SqlDbType.VarChar).Value = uname;
cmd.Parameters.Add("#password", SqlDbType.VarChar).Value = pass;
EDIT: and as #ekad said, you do not need cmd.ExecuteNonQuery();

PosterDirectory returns null

I declared the variable PosterDirectory here
SqlConnection con = new SqlConnection(Helper.GetConnectionString());
String PosterDirectory;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["Role"].ToString() != "Admin")
{
Session.Clear();
Response.Redirect("Default.aspx");
}
if (!IsPostBack)
{
GetEvent(int.Parse(Request.QueryString["EventID"].ToString()));
}
}
Supposedly PosterDirectory would be given a value within the GetEvent function.
void GetEvent(int EventID)
{
con.Open();
SqlCommand com = new SqlCommand(
"select * from event where EventID = #EventID", con);
com.Parameters.Add("#EventID", SqlDbType.Int).Value = EventID;
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
//Fill in the input fields based on the EventID
txtName.Text = reader["Name"].ToString();
txtVenue.Text = reader["Venue"].ToString();
txtStreet.Text = reader["Street"].ToString();
txtCity.Text = reader["City"].ToString();
txtCountry.Text = reader["Country"].ToString();
txtMap.Text = reader["Map"].ToString();
txtStartDate.Text = Convert.ToDateTime(reader["DateTimeStarted"].ToString()).ToString("yyyy-MM-dd");
txtStartTime.Text = Convert.ToDateTime(reader["DateTimeStarted"].ToString()).TimeOfDay.ToString();
txtEndDate.Text = Convert.ToDateTime(reader["DateTimeEnded"].ToString()).ToString("yyyy-MM-dd");
txtEndTime.Text = Convert.ToDateTime(reader["DateTimeEnded"].ToString()).TimeOfDay.ToString();
PosterDirectory = reader["Poster"].ToString();
txtDesciption.Text = reader["Description"].ToString();
}
con.Close();
}
I will use the String PosterDirectory later on for my SQL Parameter to retrieve the filepath of a photo.
protected void btnUpdate_Click(object sender, EventArgs e)
{
//Get the Date and Time Strings
DateTime DateStarted = Convert.ToDateTime(txtStartDate.Text);
TimeSpan TimeStarted = TimeSpan.Parse(txtStartTime.Text);
DateTime DateEnded = Convert.ToDateTime(txtEndDate.Text);
TimeSpan TimeEnded = TimeSpan.Parse(txtEndTime.Text);
DateTime DateTimeStarted = DateStarted + TimeStarted;
DateTime DateTimeEnded = DateEnded + TimeEnded;
//Get the DateTimeCreated
DateTime DateTimeLastUpdated;
con.Open();
//if (fuPoster.HasFile)
{
SqlCommand com = new SqlCommand(
"update event set Name=#Name, Venue=#Venue, Street=#Street, City=#City, Country=#Country, Map=#Map, DateTimeStarted=#DateTimeStarted, DateTimeEnded=#DateTimeEnded, DateTimeUpdated=#DateTimeUpdated, Poster=#Poster, Description=#Description where EventID=#EventID",
con);
com.Parameters.Add("#EventID", SqlDbType.Int).Value = int.Parse(Request.QueryString["EventID"].ToString());
com.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtName.Text;
com.Parameters.Add("#Venue", SqlDbType.NVarChar).Value = txtVenue.Text;
com.Parameters.Add("#Street", SqlDbType.NVarChar).Value = txtStreet.Text;
com.Parameters.Add("#City", SqlDbType.NVarChar).Value = txtCity.Text;
com.Parameters.Add("#Country", SqlDbType.NVarChar).Value = txtCountry.Text;
com.Parameters.Add("#Map", SqlDbType.NVarChar).Value = txtMap.Text;
com.Parameters.Add("#DateTimeStarted", SqlDbType.DateTime).Value = DateTimeStarted;
com.Parameters.Add("#DateTimeEnded", SqlDbType.DateTime).Value = DateTimeEnded;
com.Parameters.Add("#DateTimeUpdated", SqlDbType.DateTime).Value = DateTime.Now;
DateTimeLastUpdated = DateTime.Now;
if (fuPoster.HasFile)
{
com.Parameters.Add("#Poster", SqlDbType.Text).Value = "images/" + fuPoster.FileName;
fuPoster.SaveAs(Server.MapPath("images/" + fuPoster.FileName));
}
else
{
com.Parameters.Add("#Poster", SqlDbType.Text).Value = PosterDirectory;
}
com.Parameters.Add("#Description", SqlDbType.Text).Value = txtDesciption.Text;
com.ExecuteNonQuery();
con.Close();
//Auditing Event
AuditEvent(DateTimeLastUpdated);
Response.Redirect("Event.aspx");
}
//else
//{
// SqlCommand com = new SqlCommand(
// "update event set Name=#Name, Venue=#Venue, Street=#Street, City=#City, Country=#Country, Map=#Map, DateTimeStarted=#DateTimeStarted, DateTimeEnded=#DateTimeEnded, DateTimeUpdated=#DateTimeUpdated, Description=#Description where EventID=#EventID",
// con);
// com.Parameters.Add("#EventID", SqlDbType.Int).Value = int.Parse(Request.QueryString["EventID"].ToString());
// com.Parameters.Add("#Name", SqlDbType.NVarChar).Value = txtName.Text;
// com.Parameters.Add("#Venue", SqlDbType.NVarChar).Value = txtVenue.Text;
// com.Parameters.Add("#Street", SqlDbType.NVarChar).Value = txtStreet.Text;
// com.Parameters.Add("#City", SqlDbType.NVarChar).Value = txtCity.Text;
// com.Parameters.Add("#Country", SqlDbType.NVarChar).Value = txtCountry.Text;
// com.Parameters.Add("#Map", SqlDbType.NVarChar).Value = txtMap.Text;
// com.Parameters.Add("#DateTimeStarted", SqlDbType.DateTime).Value = DateTimeStarted;
// com.Parameters.Add("#DateTimeEnded", SqlDbType.DateTime).Value = DateTimeEnded;
// com.Parameters.Add("#DateTimeUpdated", SqlDbType.DateTime).Value = DateTime.Now;
// com.Parameters.Add("#Description", SqlDbType.Text).Value = txtDesciption.Text;
// DateTimeLastUpdated = DateTime.Now;
// com.ExecuteNonQuery();
// con.Close();
// //Auditing Event
// AuditEvent(DateTimeLastUpdated);
// Response.Redirect("Event.aspx");
//}
}
Members aren't persisted between requests. The Form class is only valid for a single request.
For context, read up on the ASP.NET Page Life Cycle.
You could put your value into a hidden form field or the view state.

how to pass Sql parameter

This error will come in my code Procedure or function 'gridalldata' expects parameter '#order_no', which wast not supplied. I am sending parameter to procedure like below
try
{
con.Open();
SqlCommand cmd = new SqlCommand("gridalldata", con);
cmd.Parameters.Add("#order_no", SqlDbType.NVarChar).Value = txt_orderno.Text;
SqlDataReader dr = cmd.ExecuteReader();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dr.HasRows)
{
dr.Read();
dataGridView1.Rows[i].Cells[0].Value = dr[0].ToString();
dataGridView1.Rows[i].Cells[2].Value = dr[2].ToString();
dataGridView1.Rows[i].Cells[3].Value = dr[3].ToString();
dataGridView1.Rows[i].Cells[4].Value = dr[4].ToString();
dataGridView1.Rows[i].Cells[5].Value = dr[5].ToString();
dataGridView1.Rows[i].Cells[6].Value = dr[6].ToString();
dataGridView1.Rows[i].Cells[7].Value = dr[7].ToString();
dataGridView1.Rows[i].Cells[8].Value = dr[8].ToString();
dataGridView1.Rows[i].Cells[9].Value = dr[9].ToString();
dataGridView1.Rows[i].Cells[10].Value = dr[13].ToString();
dataGridView1.Rows[i].Cells[11].Value = dr[12].ToString();
}
}
dr.Close();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
How To Fix This
Use cmd.CommandType = CommandType.StoredProcedure; to execute stored procedure.
Try This:
Try
{
con.Open();
string order= txt_orderno.Text;
SqlCommand cmd = new SqlCommand("gridalldata", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#order_no", SqlDbType.NVarChar).Value=order;
SqlDataReader dr = cmd.ExecuteReader();
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
if (dr.HasRows)
{
dr.Read();
dataGridView1.Rows[i].Cells[0].Value = dr[0].ToString();
dataGridView1.Rows[i].Cells[2].Value = dr[2].ToString();
dataGridView1.Rows[i].Cells[3].Value = dr[3].ToString();
dataGridView1.Rows[i].Cells[4].Value = dr[4].ToString();
dataGridView1.Rows[i].Cells[5].Value = dr[5].ToString();
dataGridView1.Rows[i].Cells[6].Value = dr[6].ToString();
dataGridView1.Rows[i].Cells[7].Value = dr[7].ToString();
dataGridView1.Rows[i].Cells[8].Value = dr[8].ToString();
dataGridView1.Rows[i].Cells[9].Value = dr[9].ToString();
dataGridView1.Rows[i].Cells[10].Value = dr[13].ToString();
dataGridView1.Rows[i].Cells[11].Value = dr[12].ToString();
}
}
dr.Close();
con.Close();
}
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
String orderNo=txt_orderno.Text;
// Am assuming gridalldata is your SP
SqlCommand cmd= new SqlCommand(gridalldata, connection);
cmd.CommandType=CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#order_no", orderNo);
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// Code
}
}
The using statement makes sure the connection is closed after use
Also You should bind Your Datagridview like this
Public DataTable FillDataGrid(string orderID)
{
SqlCommand cmd = new SqlCommand("gridalldata", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#order_no", orderNo);
SqlDataAdapter dap = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
dap.Fill(ds);
return ds.Tables[0];
}
Datatable dt=FillDataGrid(txt_orderno.Text);
DataGridVIew1.DataSource=dt;

Categories

Resources