Accessing Textbox from GridView data cell (ASP.NET) - asp.net

protected void GridView2_OnCommand(Object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "Reply")
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=myconnectionstring; Integrated Security = true; Connect Timeout = 30; User Instance = True";
con.Open();
string div = "','";
GridViewRow selectedRow = GridView2.Rows[Convert.ToInt32(e.CommandArgument)];
SqlCommand cmd = new SqlCommand("INSERT INTO SellerResponse VALUES ('" +
//THIS LINE IS THE ISSUE
Request.QueryString["ID"] + div + selectedRow.Cells[2].Text + div + DateTime.Now.ToString() + div + selectedRow.Cells[3].Text + ((System.Web.UI.WebControls.TextBox)(FindControl(selectedRow.Cells[1].UniqueID))).Text /*this is the cell that contains the textbox*/+ "');", con);
}
}
Any ideas how to implement this?

protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
int index = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "Reply")
{
on = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=myconnectionstring; Integrated Security = true; Connect Timeout = 30; User Instance = True";
con.Open();
string div = "','";
GridViewRow selectedRow = GridView2.Rows[Convert.ToInt32(e.CommandArgument)];
SqlCommand cmd = new SqlCommand("INSERT INTO SellerResponse VALUES ('" +
//THIS LINE IS THE ISSUE
Request.QueryString["ID"] + div + GridView2.Rows[index].Cells[2].Text + div + DateTime.Now.ToString() + div + GridView2.Rows[index].Cells[3].Text + ((System.Web.UI.WebControls.TextBox)(GridView2.Rows[index]Cells[1].FindControl("the name of the text box")).Text /*this is the cell that contains the textbox*/+ "');", con);
}
}
catch (Exception ee)
{
string message = ee.Message;
}
}
Note:1- in aspx :CommandArgument='<%#((GridViewRow)Container).RowIndex%>'
2- use RowCommand event for the grid view.

Related

Database Storing Insert Query

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
public partial class Details : System.Web.UI.Page
{
string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
string objective = " ";
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
{
String SQL = "SELECT TOP 2 * FROM QuestionBank ORDER BY NEWID()";
SqlDataAdapter Adpt = new SqlDataAdapter(SQL, con);
DataSet login1 = new DataSet();
Adpt.Fill(login1);
foreach (DataRow dr in login1.Tables[0].Rows)
{
objective = login1.Tables[0].Rows[0]["s_id"].ToString() + "," + login1.Tables[0].Rows[1]["s_id"].ToString();
Label1.Text = login1.Tables[0].Rows[0]["question"].ToString();
Label2.Text = login1.Tables[0].Rows[0]["question"].ToString();
break;
}
}
}
protected void Button1_Click(object sender, EventArgs e))
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("Insert into PaperTbl values('" + objective + "','" + TextBox1.Text + "','" + TextBox2.Text + "')", con);
cmd.ExecuteNonQuery();
Response.Write("<script>alert('Answers Saved Successfully');location.href='Details.aspx'</script>");
}
}
When i Click on Save Button
then question in the Label1 and Label2 gets changes
So the answer from textbox1 and textbox2 becomes wrong.
So while Saving the Data gets refreshed and new question gets save instead of old question. Please Help Me.
Page_Load is running before your TextBox1_TextChanged postback event. So the new values are populated and then saved.
See here for an explanation of page life cycle https://www.c-sharpcorner.com/UploadFile/8911c4/page-life-cycle-with-examples-in-Asp-Net/
This should work:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadNew();
}
}
private void LoadNew()
{
string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
string objective = " ";
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
{
String SQL = "SELECT TOP 2 * FROM QuestionBank ORDER BY NEWID()";
SqlDataAdapter Adpt = new SqlDataAdapter(SQL, con);
DataSet login1 = new DataSet();
Adpt.Fill(login1);
foreach (DataRow dr in login1.Tables[0].Rows)
{
objective = login1.Tables[0].Rows[0]["s_id"].ToString() + "," + login1.Tables[0].Rows[1]["s_id"].ToString();
Label1.Text = login1.Tables[0].Rows[0]["question"].ToString();
Label2.Text = login1.Tables[0].Rows[0]["question"].ToString();
break;
}
}
}
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("Insert into PaperTbl values('" + objective + "','" + TextBox1.Text + "','" + TextBox2.Text + "')", con);
cmd.ExecuteNonQuery();
LoadNew();
Response.Write("<script>alert('Answers Saved Successfully');location.href='Details.aspx'</script>");
}

Adding an ImageUrl to an ImageControl

I need help how to add an ImageUrl to an ImageControl programmatically. I got this code, but I can't (I don't know how) add path that is stored in database.
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath(".") + "//images//" + str);
string path = "~//images//" + str.ToString();
con.Open();
SqlCommand cmd = new SqlCommand("insert into upload values('" + TextBox1.Text + "','" + path + "')", con);
cmd.ExecuteNonQuery();
con.Close();
Label1.Text = "Image uploaded";
SqlDataAdapter da = new SqlDataAdapter("Select img from upload", con);
DataTable dt = new DataTable();
da.Fill(dt);
Image1.ImageUrl =
}
else
{
Label1.Text = "Please select image";
}
}
For that particular scenario, you already have an image filename and path. All you need is Image1.ImageUrl = ResolveUrl("~/images/" + fileName);.
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileName = FileUpload1.FileName;
string path = string.Format("{0}\\images\\{1}",
HttpRuntime.AppDomainAppPath, fileName);
FileUpload1.PostedFile.SaveAs(path);
/* Save image information to database */
Image1.ImageUrl = ResolveUrl("~/images/" + fileName);
}
else
{
Label1.Text = "Please select image";
}
}
FYI: Your code is prone to SQL Injection attack. Make sure you use Parameterized Query.

Object reference not set to an instance of an object in gridview in asp.net

I am getting this error on a row command in my gridview. Here is the code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = University.GetConnectionString();
con.Open();
string query = "select [CourseCode], [CourseNumber], [CourseName], [CRN], [Level], [Credit] from CourseTable where Term='" + MyGlobals.currentTerm + " " + MyGlobals.currentYear + "'";
SqlDataAdapter adap = new SqlDataAdapter(query, con);
DataTable tab = new DataTable();
adap.Fill(tab);
gCourses.DataSource = tab;
gCourses.DataBind();
}
}
protected void gCourses_RowCommand(object sender, GridViewCommandEventArgs e)
{
// *** Retreive the DataGridRow
int row = -1;
int.TryParse(e.CommandArgument as string, out row);
GridViewRow gdrow = gCourses.Rows[row];
DataRow dr = ((DataTable)this.gCourses.DataSource).Rows[gdrow.DataItemIndex];
string crn = dr["CRN"].ToString();
}
.
DataRow dr = ((DataTable)this.gCourses.DataSource).Rows[gdrow.DataItemIndex];
line throws the exception.
What is wrong here? Thanks
Remove the
if (!isPostback)
from your page load

how can i change the text on button at run time after click on hyperlink

i have two text-boxes a button and a gridview.
Q.1 When user enter details in the text-boxes and press submit button i want to update grid-view accordingly
Q.2 When user hits "Edit" link which is present in the gridview, i would like to change the text of submit button to Update button.
how can i do that thanks in advance
what i have tried yet:
aspx.cs code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
this.BindGrid();
string ID = Request.QueryString["ID"];
cmd = new SqlCommand("Select * from UserDetails where ID='" + ID + "'", con);
con.Open();
ad = new SqlDataAdapter(cmd);
dt.Clear();
ad.Fill(dt);
if (dt.Rows.Count > 0)
{
tbid.Text = ID;
TextBox1.Text = dt.Rows[0][1].ToString();
TextBox2.Text = dt.Rows[0][2].ToString();
}
con.Close();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Test;Integrated Security=True");
con.Open();
string Name = TextBox1.Text;
string Place = TextBox2.Text;
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "insert into UserDetails(Name,Place) values('" + Name + "','" + Place + "')";
cmd.Parameters.AddWithValue("#Name", TextBox1.Text);
cmd.Parameters.AddWithValue("#Place", TextBox2.Text);
cmd.ExecuteNonQuery();
Label1.Text = "Record Successfully inserted";
}
con.Close();
btnSubmit.Text = "Update";
TextBox1.Text = string.Empty;
TextBox2.Text = string.Empty;
}
private void BindGrid()
{
con.Open();
ad = new SqlDataAdapter("Select * from UserDetails", con);
ad.Fill(dt);
GridView1.DataSource = dt;
GridView1.DataBind();
con.Close();
}
Call a Refresh() doesn't help? I'm not sure about ASP.NET, but you have to do it in Forms.
After the user submits new data you can try to call your bindgrid method again, this way it will rebind after the new data is saved. For the edit piece, GridView has an edit template, you can try using that:
http://msdn.microsoft.com/en-us/library/ms972948.aspx

Why session is getting null while inserting the data and getting the data from SQL LITE

I have written a code to insert the data to SQL LITE database as follows
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
count = 0;
Session["x"] = "session value";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string path = Server.MapPath("bin/sampldb.db");
SQLiteConnection conn = new SQLiteConnection("Data Source=" + path + "");
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
string txt="insert into stu values("+TextBox1.Text +",'"+TextBox2.Text+"')";
cmd.CommandType = CommandType.Text;
cmd.CommandText = txt;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Label1.Visible = true;
Label1.Text = "Error:" + ex.Message;
}
}
After inserting while retrieving data Session is getting null I don't know why
protected void Button2_Click(object sender, EventArgs e)
{
if (Session["x"] != null) // Getting Null here
{
Label1.Visible = true;
Label1.Text = Session["x"].ToString();
DataSet m_oDataSet = new DataSet();
string path = Server.MapPath("bin/sampldb.db");
SQLiteConnection conn = new SQLiteConnection("Data Source=" + path + "");
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
string txt = "select * from stu";
cmd.CommandText = txt;
SQLiteDataAdapter adp = new SQLiteDataAdapter();
adp.SelectCommand = cmd;
adp.Fill(m_oDataSet);
GridView1.DataSource = m_oDataSet.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
Label1.Visible = true;
Label1.Text = "Error:" + ex.Message;
}
finally
{
conn.Close();
}
}
}
The same code when tested in Sql server 2008 works fine
protected void BtnSqlInsert_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(cnstr);
con.Open();
SqlCommand cmd = new SqlCommand("Insert into [User] values ('" + TextBox1.Text + "','" + TextBox2.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
}
protected void BtnSqlGet_Click(object sender, EventArgs e)
{
if (Session["x"] != null) //Able to get session here
{
Label1.Visible = true;
Label1.Text = Session["x"].ToString();
}
}
My sql lite path is from Bin folder as shown in image
your app writes to DB (which is in BIN folder). That causes app restart => in-proc session gets lost. You should NOT solve the consequence (by using StateServer mode), you should fix the original reason - move db file into another folder, away from BIN folder.

Resources