DetailsviewInside Linkbutton onclick it rediects and open newtab - asp.net

I am working with Details view inside details view Itemtemplete i have link button when click that link button it need to redirect and open new tab for that i use this code
protected void lnkPost_Click(object sender, EventArgs e)
{
DetailsViewRow row= (DetailsViewRow)((LinkButton)sender).NamingContainer;
int postID = Convert.ToInt32((row.FindControl("lblPostID") as Label).Text);
if (postID != null)
{
string Query = "Select * from GigPost where GigPostID='" + postID + "'";
SqlCommand cmd = new SqlCommand(Query, cn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
string Postsource = dr["PostSource"].ToString();
Response.Write("<script> window.open('"+ Postsource+"' ); </script>");
Response.End();
}
}
}
I am getting "Unable to cast object of type 'System.Web.UI.WebControls.DetailsView' to type 'System.Web.UI.WebControls.DetailsViewRow'." this error please help me how to resolve this issue
Regards,
Venkat

DetailsViewRow row = (DetailsViewRow)(((LinkButton)sender).NamingContainer);
may work - (untested)
But really - what's wrong with using the ItemCommand of the DetailsView and grab the current datakey?

Related

Submit button to update database, won't work if there is postback stated in page_load

I have a web form page that I am going to query the data from database via selecting different values from dropdown list, after I selected proper value, in the description I want to update the database record while I click the submit button, for example, customer name, and status, there will be only one record coming back and the description will show(I can do it in isPostback and query the database, using SQL DataReader and then call related index element to get it) but when I typed something in the description and click submit, it won't update in the database, but if I don't use if(isPostback) it is working.
P.S. if there is no if(ispostback) case block there,dataUpdate.Update() works well.
So my question is;
protected void btnSubmit_Click(object sender, EventArgs e)
{
dataUpdate.Update();
}
The page_load code:
protected void Page_Load(object sender, EventArgs e)
{
ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
if (!IsPostBack)
{
SqlConnection conn1 = new SqlConnection(cxInfo.ConnectionString);
string userInfoQuery1 = "select * from users where id=#id";
SqlCommand userInfo1 = new SqlCommand(userInfoQuery1, conn1);
userInfo1.Parameters.AddWithValue("#id", dropdlCx.SelectedValue);
conn1.Open();
SqlDataReader reader1 = userInfo1.ExecuteReader();
reader1.Read();
if (reader1.HasRows )
{
lblCxId.Text = "" + reader1[0];
SqlConnection conn = new SqlConnection(dataUpdate.ConnectionString);
string userInfoQuery = "select cx_first_name+',' + cx_last_name as 'name',cx_id ,incident_id,description,contact_method from incident where cx_id=#id and status=#status";
SqlCommand userInfo = new SqlCommand(userInfoQuery, conn);
userInfo.Parameters.AddWithValue("#id", lblCxId.Text);
userInfo.Parameters.AddWithValue("#status", dropStatus.SelectedValue);
conn.Open();
SqlDataReader reader = userInfo.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
lblCxId.Text = "" + reader1[0];
txtDesc.Text = (string)reader[3];
radioContact.SelectedValue = (string)reader[4];
desc= (string)reader[3];
}
conn.Close();
}
conn1.Close();
}
if (IsPostBack)
{
lblCxId.Text = dropdlCx.SelectedValue;
/*I want to have txtDesc.txt= database query here, but as long as I add the code here, then the update won't work*/
}
}
So I think there only thing I got stuck is how to let the system know that what I submit is not the thing that he is going to refresh, please accept my value instead of the refresh?

Value cannot be null in querystring

I have 2 link buttons on my page for each product.1 of them is delete that product and the other is redirect it by query string to the other page to Edit that product.
hereprotected void dlMusic_ItemCommand(object source, DataListCommandEventArgs e)
{
int id = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "EditItem")
{
Response.Redirect("~/Admin/EditMusic.aspx?id=" + id);
}
else if (e.CommandName == "DeleteItem")
{
SqlCommand cmd = new SqlCommand("", Connection);
cmd.CommandText = "DELETE FROM MusicTable WHERE MusicId=#id";
cmd.Parameters.AddWithValue("#id", id);
Connection.Open();
cmd.ExecuteNonQuery();
Connection.Close();
LoadData();
}
}
Delete button worked correctly but on edit I have problem.
protected void Page_Load(object sender, EventArgs e)
{
int id = int.Parse(Request.QueryString["id"]);
SqlDataAdapter da = new SqlDataAdapter("", Connection);
DataTable dt = new DataTable();
da.SelectCommand.CommandText = "SELECT * FROM MusicTable WHERE MusicId=#id";
da.SelectCommand.Parameters.AddWithValue("#id", id);
da.Fill(dt);
string name = dt.Rows[0]["MusicName"].ToString();
string signame = dt.Rows[0]["SingerName"].ToString();
string prodname = dt.Rows[0]["ProducerName"].ToString();
string albname = dt.Rows[0]["AlbumeName"].ToString();
string des = dt.Rows[0]["Description"].ToString();
string cover = dt.Rows[0]["Cover"].ToString();
txtMusicName.Text = name;
txtSingerName.Text = signame;
txtProducerName.Text = prodname;
txtAlbumeName.Text = albname;
coverImg.ImageUrl = "~/images/" + cover;
txtDes.InnerText = des;
}
It works correctly until requested by query string and the error come is
Additional information: Value cannot be null.
Thanks in advance
From your comment, it is apparent that field "id" is not part of your QueryString.
Please check your URL when the Edit Page is loaded by the browser (you can see it if you put a breakpoint and switch to the browser window).
If you think your URL is correct, please post a screenshot of your loading browser.
Another idea (quite desperate, though), change "id" in whatever else (i.e. "myid")
Response.Redirect("~/Admin/EditMusic.aspx?myid=" + id);
and
int id = int.Parse(Request.QueryString["myid"]);

Retrieving the image from database and displaying in web page in Asp.Net

I am trying to store the profile picture which the user uploads in a database and retrieve from the database and display in web page.I have successfully saved the image in database but I don't know how to retrieve it.I have tried to display but when I click the retrieve button nothing happens.
This is the code in Handler page and instead of retrieving the image based on Id I am trying to do it by passing the name of the user which will be on the welcome page.
public void ProcessRequest(HttpContext context)
{
//passing name here
if (context.Request.QueryString["name"] != null)
{
string csc = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(csc))
{
SqlCommand com = new SqlCommand("RetrieveImage", con);
com.CommandType = CommandType.StoredProcedure;
//passing name
SqlParameter p1 = new SqlParameter("#userName", context.Request.QueryString["name"]);
com.Parameters.Add(p1);
con.Open();
SqlDataReader dr = com.ExecuteReader();
dr.Read();
context.Response.BinaryWrite((byte[])dr["image"]);
dr.Close();
con.Close();
}
}
else
{
context.Response.Write("No Image Found");
}
}
public bool IsReusable
{
get
{
return false;
}
}
I have created a stored procedure which accepts username and gives image.Stored procedure name is "RetrieveImage"
This is the button click event.On clicking the button "RetrieveImage" it calls handler and passes value as "name"which then calls stored procedure and displays image
protected void RetrieveImage_Click(object sender, EventArgs e)
{
string csc = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(csc))
{
SqlCommand com = new SqlCommand("RetrieveImage", con);
com.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("#userName", WelcomeUsername.Text);
com.Parameters.Add(p1);
con.Open();
SqlDataReader dr = com.ExecuteReader();
ImageDisp.ImageUrl = "~/ImagePage.ashx?name=" + WelcomeUsername.Text;
con.Close();
}
}
When I run the page I am not getting any error but when I click the button nothing happens.I am new to .Net .Please help.!! Thanks in advance

I have error in updating records in database sql server

I have a problem : I have page for insert data into database , and the same page for update data based on query string for each item , the problem when i update the fields from textbox(s) , the same data is returned to update: the same data updated in database from textbox in page_load !!
In Page_Load
con.Open();
//For edit items
if (Request.QueryString["id"] != null)
{
Page.Title = "Edit Items";
DataTable dt = Get_Items(Request.QueryString["id"].ToString());
txt_item_name.Text = dt.Rows[0]["name"].ToString();
txt_end_date.Text = dt.Rows[0]["endDate"].ToString();
Btn_addItem.Text = "Edit item";
}
protected void Btn_addItem_Click(object sender, EventArgs e)
{
if (Btn_addItem.Text.Equals("Add Item"))
{
SqlCommand cmd = new SqlCommand("addedit", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#item_id", "-1");
cmd.Parameters.AddWithValue("#name", txt_item_name.Text);
cmd.Parameters.AddWithValue("#endDate", txt_end_date.Text);
con.Open();
cmd.ExecuteNonQuery();
lbl_msg.Text = "Item added....";
con.Close();
}
else
{
SqlCommand cmd = new SqlCommand("addedit", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#item_id", Request.QueryString["id"]);
cmd.Parameters.AddWithValue("#name", txt_item_name.Text);
cmd.Parameters.AddWithValue("#endDate", txt_end_date.Text);
con.Open();
cmd.ExecuteNonQuery();
lbl_msg.Text = "Item edited....";
con.Close();
}
}
If I understand your question correctly "You are not able to update the DB with the new value you enter in the textboxes. Its updating the DB with the old value again".
You need to check for !IsPostback in your Page_Load as the code for binding the textboxes from DB will be called before Btn_addItem_Click during postback and it will set the value of textboxes back to the old value from DB. See below updated code:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
con.Open();
//For edit items
if (Request.QueryString["id"] != null)
{
Page.Title = "Edit Items";
DataTable dt = Get_Items(Request.QueryString["id"].ToString());
txt_item_name.Text = dt.Rows[0]["name"].ToString();
txt_end_date.Text = dt.Rows[0]["endDate"].ToString();
Btn_addItem.Text = "Edit item";
}
}
}
Hope it helps.

I want my controls value.Insert only one time when I click the button

I have a DropDownlist and a textbox in my page, when I click the button,Button1_Click event fire and get the value od textbox and droppdownlist and send them to my table in database and it shows me the result(new added row in my table in database) in gridview.
my problem is after I click the button if I refresh my page I mean click on reload Current page ,my dropdownlist value and textbox value insert again in my table .
I don't know how solve it?
my gridview use sqldatasource and this is my code:
protected void Button1_Click(object sender, EventArgs e)
{
int brandid = Convert.ToInt32(BrandDropDownList.SelectedValue);
String catname = TextBox2.Text;
SqlConnection cn = new SqlConnection();
cn.ConnectionString = "server = . ; database = mobile_store ; Trusted_Connection=true";
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "FirstInitialiseCategories";
cmd.Parameters.AddWithValue("#brandid ", brandid);
cmd.Parameters.AddWithValue("#catname ", catname);
try
{
cn.Open();
cmd.ExecuteNonQuery();
Label1.ForeColor = System.Drawing.Color.Green;
Label1.Text = "با موفقیت ثبت شد!";
SqlDataSource2.DataBind();
GridView1.DataBind();
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
Label1.ForeColor = System.Drawing.Color.Red;
Label1.Text = "خطا در ثبت!";
}
finally
{ cn.Close(); }
}
You can do a HTTP redirect (to the same page) once you're done with your first insert, it should solve the issue:
Response.Redirect("samePage.aspx");
what is the first item in your dropdown list? you could set a null value to the first item and when you inserted value to database, you can add code to clear the text box and drop down list.
finally
{
cn.Close();
Label1.Text ="";
ddl.SelectedIndex = 0;
}

Resources