retrieve data from gridview in asp.net vb - asp.net

I've been looking for this a while but I still don't know how I can get data from the selected rouw out of a Gridview in Asp.net vb.
I tried this but then i get this: Object reference not set to an instance of an object.
Dim email As String
email = Gridview1.SelectedRow.Cells(1).Text

You have to call DataBind before:
Gridview1.DataBind();
Dim email As String
email = Gridview1.SelectedRow.Cells(1).Text

try this ...
email = GridView1.CurrentRow.Cells(1).Value.ToString()

Try this,it may work
Dim email As String
email = Gridview1.SelectedRow.Cells(1).Value.ToString()

protected void OnSelectedIndexChanged(object sender, EventArgs e)
{
//Accessing BoundField Column
string name = GridView1.SelectedRow.Cells[0].Text;
//Accessing TemplateField Column controls
string country = (GridView1.SelectedRow.FindControl("lblCountry") as Label).Text;
lblValues.Text = "<b>Name:</b> " + name + " <b>Country:</b> " + country;
}
Refer the below link.
http://www.aspsnippets.com/Articles/How-to-get-Selected-Row-cell-value-from-GridView-in-ASPNet.aspx

Related

access database wont update asp.net [duplicate]

my access database wont update with this code. what seems to be the problem?
i have tried a lot of methods for updating my access database with no sucsess
please guys some help.
protected void Btnupdate_Click(object sender, EventArgs e)
{
foreach (RepeaterItem RI in rptEdit.Items)
{
Label id = RI.FindControl("Pid") as Label;
TextBox prdname = RI.FindControl("prdname") as TextBox;
TextBox prdprice = RI.FindControl("prdprice") as TextBox;
TextBox prdshortdesc = RI.FindControl("prdshortdesc") as TextBox;
TextBox prdtype = RI.FindControl("prdtype") as TextBox;
TextBox prdbrand = RI.FindControl("prdbrand") as TextBox;
int updated;
string connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Table.accdb";
using (var conn = new OleDbConnection(connection))
{
conn.Open();
string updSql = #"UPDATE ProductList SET
Pname = '" + prdname.Text + "' WHERE Pid = ?";
using (var cmd = new OleDbCommand(updSql, conn))
{
cmd.Parameters.Add("#Pname", OleDbType.VarChar).Value = prdname.Text;
updated = cmd.ExecuteNonQuery();
conn.Dispose();
conn.Close();
}
}
}
}
Just use the ? style parameters in your SQL.
string sql = #"UPDATE ProductList SET Pname = ? WHERE Pid = ?";
Then just make sure you add your parameters in the same order in your code that they appear in the SQL.
cmd.Parameters.Add(prdName.Text);
cmd.Parameters.Add(int.Parse(id.Text));
You need to make sure the type of the variable being added in C# matches the type in the DB (in terms of text or number). Then it can be properly quoted or not as needed.

Check at run time if primary key exists

I am working in asp.net. I have a textbox named formidtxt and another textbox is colortxt. Now what I want is that when a user enters an Form ID in formidtxt then at the same time it should start checking whether there already exists a form id with same ID that has been entered and if Form ID already exists in database then the color of colortxt textbox should change to red else it should be green.
I have an idea that it can be done by using events in text boxes but can't understand the working. My database is in SQL Server 2008.
Try this C# code;
private void Page_Load(object sender, EventArgs e)
{
// formidtxt is the name of the textbox
this.formidtxt.TextChanged += FormIDTextBox_TextChanged;
formidtxt.AutoPostBack = true;
}
Note that this method was written inside the Page_Load method.
TextChanged is an event and it occurs when the text is modified in a TextBox.
In this case, when the formidtxt (textbox) text changes, it will call the FormIDTextBox_TextChanged method.
private void FormIDTextBox_TextChanged(object sender, EventArgs e)
{
int x = 0;
// convert textbox text (string) to int
Int32.TryParse(formidtxt.Text, out x);
// call IsIDAvailableDAO method
// x is the converted int value
if (IsIDAvailableDAO(x))
{
colortxt.BackColor = System.Drawing.Color.Red;
}
else
{
colortxt.BackColor = System.Drawing.Color.Green;
}
}
This method will get the text from the textbox (formidtxt) and send it to the IsIDAvailableDAO method as a parameter.
Using the IsIDAvailableDAO method, we can check whether the ID is available in the database or not. If it is available, then the method will return a TRUE boolean value. If not, it will return a False boolean value.
According to that boolean value, you can change the color of the colortxt textbox as you want or do something else.
private Boolean IsIDAvailableDAO(int id)
{
Boolean output;
using (SqlConnection myConnection = new SqlConnection("Data Source=localhost;Initial Catalog=Testing;Integrated Security=True"))
{
string query = #"SELECT CASE WHEN COUNT(ID) >= 1 THEN CAST( 1 as BIT ) ELSE CAST( 0 as BIT )
END As IsAvailable
FROM TableName
WHERE ID = #ID";
SqlCommand cmd = new SqlCommand(query, myConnection);
cmd.Parameters.AddWithValue("#ID", id);
myConnection.Open();
output = (Boolean)cmd.ExecuteScalar();
myConnection.Close();
}
return output;
}
In this method (IsIDAvailableDAO), Please change the query (TableName, ID, etc.) and connectionstring as appropriate.
You also has to add this namespace: using System.Data.SqlClient;
https://www.connectionstrings.com/sql-server-2008/
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/namespaces/using-namespaces

I cannot pass more than one value in QueryString

My ASP.NET application has stopped working after I migrated it to another server.
The problem is that I cannot send more than one value via the query string.
The URL I'm trying looks like this:
ThisIsSecondPage.aspx?Mode=Edit&ID=0001
I can capture the value of Mode in ThisIsSecondPage.aspx, but ID is blank.
I also tried to change ID to something line A0001, but it did not work.
I also tried:
ThisIsSecondPage.aspx?Mode=Edit<and>ID=0001
Can anyone help me please?
send querystring like this
ThisIsSecondPage.aspx?Mode=Edit&ID=0001
and recive in page_load event of ThisIsSecondPage page:
protected void Page_Load(object sender, EventArgs e)
{
string ModeParam = "";
string IDparam = "";
if(Request.Params["Mode"] !=null)
ModeParam = Request.Params["Mode"].ToString();
if (Request.Params["ID"] != null)
IDparam = Request.Params["ID"].ToString();
}
You are passing query string correctly.
ThisIsSecondPage.aspx?Mode=Edit&ID=0001
In second page, Use as below
For Mode
string ModeValue = Request.QueryString["Mode"];
or in short form,
string ModeValue = Request["Mode"];
For ID
string IDValue = Request.QueryString["ID"];
or in short form,
string IDValue = Request["ID"];

Row is not updating in gridview in asp.net

I am using update commandField in Gridview. the Textbox used in gridview returning old value. the code for this.
string id = ((Label)GridView1.Rows[e.RowIndex].FindControl("Label6")).Text;
string name = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox1")).Text;
string number = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox2")).Text;
string mail = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox3")).Text;
string address = ((TextBox)GridView1.Rows[e.RowIndex].FindControl("TextBox4")).Text;
string s = "update contacts set c_name='"+name+"', c_number='"+number+"', c_mail = '"+mail+"', c_address = '"+address+"' where contact_id = "+id+"";
getsqlConnection();
dbConnection.Open();
MySqlCommand cmd = new MySqlCommand(s, dbConnection);
cmd.ExecuteNonQuery();
GridView1.EditIndex = -1;
loadcontacts();
Please Help...
if (!IsPostBack)
{
}
This code at Page Load solved my problem.

Getting error in ASP.Net page

Can you please let me know why the following piece of code is not working, I am getting the error message when the debugger past the variable "strStatus". The error message is: "Object reference not set to an instance of an object." Can you please help. Thanks - Yagya
protected void Button1_Click(object sender, EventArgs e)
{
if (Y0130_chkNew.Checked == true)
{
bool isChecked = true; // This is required for later retrieval.
string strAction = "Reporting";
string strFromRole = ddSelectRole.SelectedValue;
string TxtBoxID = myProject.getTextBox(strAction, strPath);
TextBox txtb = new TextBox();
txtb = (TextBox)Page.FindControl(TxtBoxID);
string strStatus = txtb.Text;
string ddID = myProject.getDropDown(strAction, strPath);
DropDownList ddLst = new DropDownList;
ddLst = (DropDownList)Page.FindControl(ddID);
string strForwardRole = ddLst.SelectedValue;
// Call the function now
my.updateXML(strFromRole, strAction, strStatus, strForwardRole, strPath);
}
}
Page.FindControl(TxtBoxID); returns null what is the reason for your exception. FindControl does not search controls recursively, only in the given NamingContainer.
If the control is not nested in another NamingContainer on the page(f.e. a GridViewRow), there's no reason at all to use FindControl since you could reference it directly:
string strStatus = TextBox1.Text; // assuming TextBox1 is declared on the aspx
If you're using MasterPages the NamingContainer of controls in the ContentPage is not the page but the ContenPlaceHolder:
Cannot find TextBox on Page
You are finding a control using a function and possibly its returning a textbox id which doesnt existin on page . Please try to debug and see what textbox id you are getting from myProject.getTextBox function and if that exist on page .
Final Code:
if (Y0130_chkNew.Checked == true)
{
string TxtBoxID = "Y0140_txtStatus";
TextBox txtb = new TextBox();
txtb = (TextBox)Page.Master.FindControl("ContentPlaceHolder1").FindControl(TxtBoxID);
string strStatus = txtb.Text;
string ddID = "Y0150_ddOwnerRoleAssignment";
DropDownList ddLst = new DropDownList();
ddLst = (DropDownList)Page.Master.FindControl("ContentPlaceHolder1").FindControl(ddID);
string strForwardRole = ddLst.SelectedValue;
}

Resources