I want to display the mysql table's contents into gridview - asp.net

what can I do when my all database table's name into dropdown list & when i select or click the table name from dropdown list display the whole field into the gridview dynamically..please give me best solution in asp.net.

Use the mysql commands SHOW TABLES and DESCRIBE table_name and draw the result into grids. I don't know the ASP codes.

(This is an example for MSSQL db. For mysql you can try using OdbcConnection or OleDbConnection depending on MySql version.)
1.Here is direct way to select data:
public class DAL
{
public static DataTable GetTableData(string tableName)
{
DataTable dt = new DataTable();
using (SqlConnection cn = new SqlConnection(Settings.Default.ConnectionString))
{
cn.Open();
SqlCommand cmd = cn.CreateCommand();
cmd.CommandText = string.Format("select * from {0}", tableName);
using (SqlDataReader rd = cmd.ExecuteReader())
{
bool ColumnsAdded = false;
while (rd.Read())
{
if (!ColumnsAdded)
{
for (int i = 0; i < rd.FieldCount; i++)
dt.Columns.Add(rd.GetName(i), rd.GetFieldType(i));
}
DataRow row = dt.NewRow();
for (int i = 0; i < rd.FieldCount; i++)
row[i] = rd[i];
dt.Rows.Add(row);
ColumnsAdded = true;
}
}
}
return dt;
}
}
2.Next you drop ObjectDataSource onto your form with a GridView (setting its DataSourceID to objectdatasource). Specify this method on your ObjectDataSource select method. You can specify parameter for tableName to be read from Control (DropDownList1 for instance). DropDownList1 presumebly keeps a list of tables.

You can dynamically load the table contents into gridview by putting a select query for the table and then bind that dataset to gridview datasource.
Hope this helps you!!

Related

How to insert dropdownlist value, text box value and gridviews selected row together?

How to insert dropdownlist value, text box value and gridviews selected row together?
Also attached the screenshot of the data insert:
enter image description here
enter image description here
enter image description here
I tend to prefer a add button that adds a row to the grid, and THEN you let the user edit the one row.
However, assuming you have those text boxes at the top of the screen, enter data, and then click a button to add to the database, and then re-fresh the GV?
I also don't see some button in the top area to add the data?
so, say a button added to the top area?
then this would add the row to the database:
protected void Button3_Click(object sender, EventArgs e)
{
string strSQL =
"INSERT INTO MyTable (Session, Class, Section, Term, Subject, HighestMark) " +
"VALUES (#Session, #Class, #Seciton, #Term, #Subject, #HighestMark)";
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL,conn))
{
conn.Open();
cmdSQL.Parameters.Add("#Session", SqlDbType.Int).Value = DropSession.selecteditem.value;
cmdSQL.Parameters.Add("#Class", SqlDbType.Int).Value = DropClass.selecteditem.value;
cmdSQL.Parameters.Add("#Section", SqlDbType.Int).Value = DropSection.selecteditem.value;
cmdSQL.Parameters.Add("#Term", SqlDbType.Int).Value = DropTerm.selecteditem.value;
cmdSQL.Parameters.Add("#Subject", SqlDbType.Int).Value = DropSubject.selecteditem.value;
cmdSQL.Parameters.Add("#HighestMark", SqlDbType.Int).Value = HighestMark.Text;
cmdSQL.ExecuteNonQuery();
}
}
ReloadGrid(); // call routine to refresh the grid.
}
Edit: Adding the rows to a new table
Ok, so we are to take the top values, and then process each row of the grid, and take the ones with a check box and "insert" this data into a new table.
Ok, so the code will look like this:
protected void Button1_Click(object sender, EventArgs e)
{
string strSQL = "SELECT * FROM tblHotelsA WHERE ID = 0";
DataTable rstData = MyRst(strSQL);
foreach (GridViewRow gRow in GHotels.Rows)
{
CheckBox ckChecked = gRow.FindControl("ckSelected") as CheckBox;
if (ckChecked.Checked)
{
// this row was checked - add a new row
DataRow MyNewRow = rstData.NewRow();
MyNewRow["HotelName"] = txtHOtelName.Text; // exmaple control
MyNewRow["City"] = txtCity.Text; // example control above grid
// values from grid row
// tempalted columns, we use find control
MyNewRow["FirstName"] = (gRow.FindControl("txtFirstName") as TextBox).Text;
MyNewRow["LastName"] = (gRow.FindControl("txtLastName") as TextBox).Text;
// if data bound column, then we use cells collection
MyNewRow["FavorateFood"] = gRow.Cells[5];
// etc. etc.
rstData.Rows.Add(MyNewRow);
}
}
// done adding to table, write/save back to database.
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
SqlDataAdapter da = new SqlDataAdapter(cmdSQL);
SqlCommandBuilder daU = new SqlCommandBuilder(da);
cmdSQL.Connection.Open();
da.Update(rstData);
}
}
}
I also had this helper routine - I often use it all over the palce:
public DataTable MyRst(string strSQL)
{
DataTable rstData = new DataTable();
using (SqlConnection conn = new SqlConnection(Properties.Settings.Default.TEST4))
{
using (SqlCommand cmdSQL = new SqlCommand(strSQL, conn))
{
cmdSQL.Connection.Open();
rstData.Load(cmdSQL.ExecuteReader());
}
}
return rstData;
}
So, the concept here?
I pulled a blank row (SELECT * from table where ID = 0).
This gets me the database structure - and thus avoids a BOATLOAD of parameters in the sql.
this approach ALSO allows me to add a row to the table, and add "many" rows. And then execute ONE update to the database to write out (save) all the rows in one shot. So, this again reduced quite a bit of messy code.

Add Session data to ListBox

I didn't write all code. It just a part of sessions which has already data inside. I just want to get all data from sessiosn by which Session["sepet"] to add Listbox but I couldn't do that. There is no any error message. Actually the code purpose is, I wanted to add all data to Listbox after that I want to send all data what include the Listbox to SQL Database. I don't know is there any different way to do.
private void SepetGetir1()
{
List<string> lst = new List<string>();
if (Session["sepet"] != null)
{
DataTable dt = new DataTable();
dt = (DataTable)Session["sepet"];
foreach (DataRow r in dt.Rows)
{
lst.Add(r["ID"].ToString());
lst.Add(r["productName"].ToString());
}
ListBox1.DataSource = lst;
}
}
You can bind the data table to the ListBox, and specify which field is used for Text and wihch one is used for Value:
DataTable dt = Session["sepet"] as DataTable;
ListBox1.DataSource = dt;
ListBox1.DataTextField = "productname";
ListBox1.DataValueField = "ID";
ListBox1.DataBind();

Stored procedure doesnt return any value

I got simple problem but I got no idea about where is problem :/ So in my GridView I am using ObjectDataSource with custom paging like in this tutorial http://www.codedigest.com/Articles/ASPNET/180_Custom_GridView_Paging_with_ObjectDataSource_Control_with_ASPNet_20.aspx
Here is my aspx markup:
<asp:ObjectDataSource ID="ObjectDataSource2"
runat="server"
onselecting="ObjectDataSource2_Selecting"
EnablePaging="true"
SelectCountMethod="GetItemsCount"
SelectMethod="BindItems"
StartRowIndexParameterName="startRowIndex"
MaximumRowsParameterName="maximumRows"
TypeName="eSova.Utilities.RecordUtilities"
>
And method which calling:
public static DataTable BindItems(int category,int search,int startRowIndex,int maximumRows)
{
DataTable table = new DataTable();
using (SqlConnection connection = new SqlConnection())
{
ConnectionUtilities.OpenConnection(connection);
SqlTransaction transaction = connection.BeginTransaction();
try
{
SqlCommand command = new SqlCommand("GetItems",connection,transaction);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add("#RowIndex", SqlDbType.Int, 4).Value = startRowIndex;
command.Parameters.Add("#MaxRows", SqlDbType.Int, 4).Value = maximumRows;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(table);
transaction.Commit();
}
catch
{
transaction.Rollback();
}
}
return table;
}
My stored procedure works just fine and return in all items from table.
But when I analyze the code, I got breakpoint on return and table variable is without records. I don't know where is problem.
UPDATE:
create proc [dbo].[GetItems](#RowIndex int,#MaxRows int)
as
declare #StartRows int
declare #EndRow int
set #StartRows=(#RowIndex+1)
set #EndRow=(#StartRows+#MaxRows)
select *
from ( select id, name, filepath, descript, itemlanguage,
filetypeid, ROW_NUMBER() over (ORDER by id)as row FROM Items)as NumberesItems
where row between #StartRows and #EndRow
Your connectionstring is empty.

binding dropdownlist values to textbox

When the user selects an order ID, the rest of the order information is displayed in label(s). Display the following: employee ID, order date, freight, shipped name, and country. This functionality should be implemented using direct data access programmatically.
Edit: code example and additional explanation.
String CS = onfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionStr‌​ing;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT OrderID FROM Orders", con);
con.Open();
DropDownList1.DataSource = cmd.ExecuteReader();
DropDownList1.DataTextField = "OrderID";
DropDownList1.DataValueField = "OrderID";
DropDownList1.DataBind();
Label1.Text = Convert.ToString(DropDownList1.SelectedItem.Text);
}
What I want is the other fields which are there in orders table to be displayed when a value is selected in the dropdownlist.
Can you make datatable from the SQL Query result, and then add items to dropdownlist from ID column. When you then select an item from DDL, you show the info where the row from datatable match the selected orderID.
I can write code if you want it isn't cleared what I'm meaning.
UPDATE: with code
var ds = new DataSet();
using (var conn = new SqlConnection(connection))
{
conn.Open();
var command = new SqlCommand("Your SQL Query", conn);
var adapter = new SqlDataAdapter(command);
adapter.Fill(ds);
conn.Close();
} //Now you have a dataset, with one table that matches your query result.
//And now we can use a foreach loop to add every OrderID to dropdownlis
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
DDLname.Items.Add(dr[0].ToString());
}
}
//onSelectedValue event
string orderID = DDLname.Text.toString();
Label1.Text = orderID;
foreach (DataTable table in ds.Tables)
{
foreach (DataRow dr in table.Rows)
{
if(dr[0].toString().equals(orderID))
{
Label2.text = dr[1].toString();
Label3.text = dr[2].toString();
etc....
}
}
}
As you labelled your question with ASP.Net, I assume that this is part of an ASP.Net Webforms application. This means that the drop down list will be inside a web page in a browser. Not clear to me is whether you want the label to be displayed immediately when the user select the item, or only after a post to the server.
In the first case, you'll need javascript and probably something like Ajax or JSON to get the data you want to display for the selected item. In the second case, you could add an event handler for the SelectedIndex_Changed Event of your drop down list. This handler should do something like this:
string CS = ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("SELECT OrderID FROM Orders WHERE OrderId = #OrderId", con);
cmd.Parameters.AddWithValue("#OrderId", DropDownList1.SelectedItem.Value);
con.Open();
if (reader.Read())
{
SqlDataReader reader = cmd.ExecuteReader();
Label1.Text = String.Format("Employee ID: {0}, order date: {1}, freight: {2}, shipped name: {3}, and country {4}."
, reader["employeeid"].ToString()
, reader["orderdate"].ToString()
, reader["freight"].ToString()
, reader["shipname"].ToString()
, reader["shipcountry"].ToString());
}
}

asp.net gridview template column

In my asp.net gridview, I am placing a template column which displays an image.
Inside the template column I added an image control, and it successfully displaying the images from the database. I am also using paging.
Paging also happening but when I do paging images are not coming in the gridview in proper order for example first three pages it diplays suppose a.jpg, b.jpg,c.jpg and when I click on page number it repeats the same picture instead of remaining pictures, i am using if(!ispostback) in the load event also. please help me out.
my code in page load event is:
da = new SqlDataAdapter("select * from t1", con);
ds = new DataSet();
da.Fill(ds);
path = Server.MapPath(#"~\images");
if (!IsPostBack)
{
GridView1.DataSource = ds;
GridView1.DataBind();
ASCIIEncoding asc = new ASCIIEncoding();
int j = GridView1.Rows.Count;
for (int i = 0; i < j; i++)
{
GridViewRow r=GridView1.Rows[i];
b = (byte[])ds.Tables[0].Rows[i]["photo"];
string name = asc.GetString(b);
Image img = (Image)r.FindControl("Image1");
img.ImageUrl = path + #"\" + name;
}
}
and my code in paging event is
GridView1.PageIndex = e.NewPageIndex;
GridView1.DataSource = ds;
GridView1.DataBind();
ASCIIEncoding asc = new ASCIIEncoding();
int j = GridView1.Rows.Count;
for (int i = 0; i < j; i++)
{
GridViewRow r=GridView1.Rows[i];
b = (byte[])ds.Tables[0].Rows[i]["photo"];
string name = asc.GetString(b);
Image img = (Image)r.FindControl("Image1");
img.ImageUrl = path + #"\" + name;
}
thank in advance
sangita
When you write your paging method you still need to re-query the datasource and rebind your gridview (along with setting the PageIndex).
assuming that you have only the image name stored in the database you can do this in the Image Control in you template column
set the databinding for the image url as
String.Format("images/{0}",Eval("photo"))
and as boon has said
When you write your paging method you
still need to re-query the datasource
and rebind your gridview (along with
setting the PageIndex).
you can declare a method that fetches the records from the database as
protected void fillData()
{
da = new SqlDataAdapter("select * from t1", con);
ds = new DataSet();
da.Fill(ds);
GridView1.DataSource = ds;
GridView1.DataBind();
}
and use it to bind data to your gridview
and in your paging_indexChanging function
GridView1.PageIndex = e.NewPageIndex;
fillData();
Please verify the image paths in pagination. If the images paths are same, then disable the browser cache.

Resources