• 15 апреля стартует «Курс «SQL-injection Master» ©» от команды The Codeby

    За 3 месяца вы пройдете путь от начальных навыков работы с SQL-запросами к базам данных до продвинутых техник. Научитесь находить уязвимости связанные с базами данных, и внедрять произвольный SQL-код в уязвимые приложения.

    На последнюю неделю приходится экзамен, где нужно будет показать свои навыки, взломав ряд уязвимых учебных сайтов, и добыть флаги. Успешно сдавшие экзамен получат сертификат.

    Запись на курс до 25 апреля. Получить промодоступ ...

как получить Id файла, который только загрузили в базу Sql

  • Автор темы Kreol
  • Дата начала
K

Kreol

Вот выташил описание, но только не понял где и как его писать? Это в хендлере писать или в страничке откуда он должен поступить? и как тогда получить его значение на 2 страничке
Коллекция Request.QueryString

Коллекция QueryString получает значения переменных их HTTP-строки запроса. Строка запроса определяется значениями, следующими за знаком вопроса (?). Некоторые различные процессы могут генерировать строку запроса. Для примера, таг анкор

Строка примера

вырабатывает значение с имененм String и значением "this is sample". Строка запроса также генерируется при передачи данных при обработке формы или прямым вводом строки пользователем прямо в браузер (строка адреса).

Синтакс:

Request.QueryString( переменная ) [ ( индекс ) | .Count ]

Параметры:

переменная
Имя переменной, через котурую будет передаваться значение.
индекс
Не обязательный параметр, который позволяет вам получить доступ к одному из значений параметра (в том случае если передано не одно значение). Это может быть любое значение (целочисленное) в диапазоне от 1 до Request.QueryString(элемент).Count.
 
K

Kreol

если я пишу
Код:
imgDB.ImageUrl="~/ViewPicture.ashx";
то оно мне на хендлер не переключается, и даже если
Код:
imgDB.ImageUrl="~//ViewPicture.ashx?id=20";
тоже не выводит

а не это я ежик, не поставил свойство визибле имейджу :)

только почему-то , когда я пишу просто
Код:
imgDB.ImageUrl="~/ViewPicture.ashx";
то оно не выводит картинку, только когда я указываю точный id но мне нужно получать картинку с id который записан уже в
Код:
int Id = int.Parse(context.Request.QueryString["id"]);
что сделать?
 
K

Kreol

да я уже понял, мозги на бекрень уже куда-то встали, нана на пиво идти :)
Код:
imgDB.ImageUrl = "~/ViewPicture.ashx?id=" + id + "";
только вопросик, как мне объявить переменную которая будет глобальная для всего кода?
и которая будет получать например id из функции а передавать ее совершенно другой процедуре

и почему при когда записываешь большие картинки, то при выводе из базы они пиксилизируются? тоесть теряется страшно качество
 
K

Kreol

Что-то я запутался, как передать параметр pic
из
Код:
protected void cmdSend_Click(object sender, EventArgs e)
byte[] pic = new byte[len];
filMyFile.PostedFile.InputStream.Read(pic, 0, len);

в
Код:
protected void ImgBtn_Greate_Good_Click(object sender, ImageClickEventArgs e)
command.Parameters.AddWithValue("@picture", pic);
 
K

Kreol

Приветик. Вот запнулся

Код:
using System;
using System.IO;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;

public partial class Main : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

if (!Page.IsPostBack)
{

string ConnectionString = ConfigurationSettings.AppSettings.Get("ConnectionString");
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
//p.242 Разработка Web приложений
connection.Open();
SqlCommand command = new SqlCommand("AddG", connection);
SqlDataAdapter adapt = new SqlDataAdapter("SELECT id_goods,comment from AddG", connection);
DataSet ds = new DataSet();
adapt.Fill(ds, "AddG");

DataList1.DataSource = ds;
//decimal id_goods = (decimal)command.ExecuteScalar();
//Img_View1.ImageUrl = ~/Handler_View_Image.ashx?id=" + id_goods + "";
DataList1.DataBind();

}
finally
{
connection.Close();
}
}

}
}
как при таком раскладе вывести через хендлер рисунок в даталист?

Код:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Main.aspx.cs" Inherits="Main" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body bgcolor="#009966">
<form id="form1" runat="server">
<div>
<asp:Image ID="Logo" runat="server" ImageUrl="~/Images/Menu/logo-auto.gif"/>
<Table style="height: auto; Width: auto" border="0">  


<!--Menu -->
<td style="top; height: 100px; Width: 155px" align="justify" >

<asp:ImageButton ID="ImgBtn_Main" runat="server" ImageAlign="Top" ImageUrl="~/Images/Menu/Main.gif" PostBackUrl="~/Main.aspx"></asp:ImageButton>
<asp:ImageButton ID="ImgBtn_Login" runat="server" ImageUrl="~/Images/Menu/Login.gif" PostBackUrl="~/Default.aspx"></asp:ImageButton>
<asp:ImageButton ID="ImgBtn_ShoppingCart" runat="server" ImageUrl="~/Images/Menu/ShoppingCart.gif" PostBackUrl="~/ShoppingCart.aspx"></asp:ImageButton>
<asp:ImageButton ID="ImgBtn_Purchase" runat="server" ImageUrl="~/Images/Menu/Purchase.gif" PostBackUrl="~/Purchase.aspx"></asp:ImageButton>
<asp:ImageButton ID="ImgBtn_Order" runat="server" ImageUrl="~/Images/Menu/Order.gif" PostBackUrl="~/Order.aspx"></asp:ImageButton>
<asp:ImageButton ID="ImgBtn_Add_Good" runat="server" ImageUrl="~/Images/Menu/Add Good.gif" PostBackUrl="~/AddGoods.aspx"></asp:ImageButton>
</td> 

<!--End Menu -->
<td>


<asp:DataList ID="DataList1" runat="server">
<ItemTemplate>
[size=3][color=#3366FF]<asp:Image ID="Image1" runat="server" ImageUrl='~/Handler_View_Image.ashx?id_goods=10'/>[/color] [/size]				<asp:Label ID="Lbl_comment" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.comment") %>'></asp:Label>
<asp:Label ID="Label1" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.id_goods") %>'></asp:Label>											 
</ItemTemplate>
</asp:DataList>
</td>
<!--MAIN CODE-->	  

</Table>


</div>
</form>
</body>
</html>
 
K

Kreol

Код:
Compilation Error 
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 

Compiler Error Message: CS1026: ) expected

Source Error:



Line 31:			 <asp:DataList ID="DataList1" runat="server">
Line 32:			 <ItemTemplate>
Line 33:				 <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("id_goods", "~/Handler_View_Image.ashx?id_goods={0}" %>' ></asp:Image>
Line 34:				 <asp:Label ID="Lbl_comment" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.comment") %>'></asp:Label>
Line 35:				 <asp:Label ID="Label1" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.id_goods") %>'></asp:Label>		  
Source File: d:\123\WEBB\WebSite1\Main.aspx	Line: 33
неправильное помойму пропись синтаксиса
Eval(Container, "DataItem.ххх")
 
K

Kreol

там синтаксис не подсвечивается, я не знаю что там не закрыто
 
K

Kreol

:huh: виноват!!!
заработало. :)
только вопросик, какой поставить тип для описания товара?
хочется чтобы оно его выводило в форматированом виде абзацами и тд. А то nvarchar(200) получается просто в строчку пишет. И какой под них нужен объект? текстбох не подходит же, там все в строчку
 
K

Kreol

Это выбрать нтмлтехт и там пряммо вводить, а как его тогда в базу записывать?
 
K

Kreol

да так и столкнулся. Если вводить большой форматированый текст TextBox(Textmode=multilain) то он то в базу пишет но при этом не происходит отображения картинки при сохранении на страничке, но это пол беды. Потом из базы он нифига не считывается. вообще не отображается
 
K

Kreol

Вывод :
Код:
using System;
using System.IO;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;

public partial class Main : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

if (!Page.IsPostBack)
{

string ConnectionString = ConfigurationSettings.AppSettings.Get("ConnectionString");
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
//p.242 Разработка Web приложений
connection.Open();
SqlCommand command = new SqlCommand("AddG", connection);
SqlDataAdapter adapt = new SqlDataAdapter("SELECT id_goods,comment from AddG", connection);
DataSet ds = new DataSet();
adapt.Fill(ds, "AddG");
DataList1.DataSource = ds;			 
DataList1.DataBind();
}
finally
{
connection.Close();
}
}

}

}
Код:
<asp:DataList ID="DataList1" runat="server" OnSelectedIndexChanged="DataList1_SelectedIndexChanged">
<ItemTemplate>
<asp:Image ID="Img_View" runat="server" ImageUrl='<%# Eval("id_goods", "~/Handler_View_Image.ashx?id_goods={0}" )%>' ></asp:Image>
<asp:Label ID="Lbl_comment" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.comment") %>'></asp:Label>
<asp:Label ID="Label1" runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.id_goods") %>'></asp:Label>											 
</ItemTemplate>
</asp:DataList>
Запись:
Код:
using System;
using System.IO;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;

public partial class AddGoods : System.Web.UI.Page
{
protected void ImgBtn_Greate_Good_Click(object sender, ImageClickEventArgs e)
{

// Check to see if file was uploaded "Проверить, что адрес не пуст"
if (filMyFile.PostedFile != null)
{
// Get a reference to PostedFile object "Получить ссылку на объект"
HttpPostedFile myFile = filMyFile.PostedFile;

// Get size of uploaded file "Получить размер файла"
int nFileLen = myFile.ContentLength;

// make sure the size of the file is > 0 "Удостоверится, что размер файла > 0"
if (nFileLen > 0)
{

// Allocate a buffer for reading of the file "Подготовить буфер для чтения файла"
byte[] myData = new byte[nFileLen];

// Read uploaded file from the Stream "Прочитать загруженый файл из потока"
myFile.InputStream.Read(myData, 0, nFileLen);

// Create a name for the file to store "Создать название файла для того, чтобы хранить"
string strFilename = Path.GetFileName(myFile.FileName);

// Write data into a file "Записать данные в файл"
WriteToFile(Server.MapPath(strFilename), ref myData);

// Set label's text "Текст ярлыка"
Lbl_AddImage.Text =
"Filename: " + strFilename + "<br>" +
"Size: " + nFileLen.ToString() + "<p>";
// Set URL of the the object to point to the file we've just saved
// "Передать путь файла который только что записали"
Img_AddImage.ImageUrl = strFilename;
Img_AddImage.ToolTip = "This file was stored to as file.";
Lbl_AddImage.Text = Img_AddImage.ImageUrl;

// show the images and text "Показать рисунок и текст"
this.Img_AddImage.Visible = true;
//imgDB.Visible = true;
this.Lbl_AddImage.Visible = true;
//lblText2.Visible = true;

// Writes file to the database
//==============================
// Create a byte[] from the input file
int len = filMyFile.PostedFile.ContentLength;
byte[] pic = new byte[len];
filMyFile.PostedFile.InputStream.Position = 0;
filMyFile.PostedFile.InputStream.Read(pic, 0, len);

//return pic;
// Insert the image and comment into the database
string ConnectionString = ConfigurationSettings.AppSettings.Get("ConnectionString");
SqlConnection connection1 = new SqlConnection(ConnectionString);
try
{
connection1.Open();
SqlCommand command1 = new SqlCommand("insert into AddG " + "(name_goods,description_goods,cost_goods,comment,picture) values (@name_goods,@description_goods,@cost_goods,@comment,@picture)\n SELECT SCOPE_IDENTITY()", connection1);

command1.Parameters.AddWithValue("@name_goods", this.TB_NameGood.Text);
command1.Parameters.AddWithValue("@description_goods", this.TB_Description.Text);
command1.Parameters.AddWithValue("@cost_goods", this.TB_Cost.Text);
command1.Parameters.AddWithValue("@comment", this.TB_Comment.Text);
command1.Parameters.AddWithValue("@picture", pic);
SqlDataReader adapter;
adapter = command1.ExecuteReader();
}
finally
{
connection1.Close();
this.Lbl_info.Visible = true;
this.Lbl_info.Text = "Thanks, the goods are added. For entering the new goods press New Good";
}
}
}
}

// Writes file to current folder "Записать файл в текущую папку"
private void WriteToFile(string strPath, ref byte[] Buffer)
{
// Create a file "Создать файл"
FileStream newFile = new FileStream(strPath, FileMode.Create);
// Write data to the file "Записать данные к файлу"
newFile.Write(Buffer, 0, Buffer.Length);
// Close file "Закрыть файл"
newFile.Close();
}

// Reads the name of current web page
private string GetMyName()
{
// Get the script name
string strScript = Request.ServerVariables["SCRIPT_NAME"];
// Get position of last slash
int nPos = strScript.LastIndexOf("/");
// Get everything after slash
if (nPos > -1)
strScript = strScript.Substring(nPos + 1);
return strScript;
}



protected void Btn_New_Goods_Click(object sender, EventArgs e)
{
this.TB_NameGood.Text = "";
this.TB_Description.Text = "";
this.TB_Cost.Text = "";
this.TB_Comment.Text = "";
this.Img_AddImage.Visible = false;
this.Img_AddImage.ImageUrl = "";
this.Lbl_AddImage.Text = "";
this.Lbl_info.Text = "";

}
}
 
K

Kreol

тоесть, но работает же, это я переписывал из варианта рабочего с ВБ.НЕТ
Код:
Imports System
Imports System.Web
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlClient

Partial Class ShoppingCart
Inherits System.Web.UI.Page

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

Dim txt As String = ""
Dim productSum As Integer = 0
Dim i As Integer = 0

For i = 0 To Me.DataList1.Items.Count - 1

Dim c As CheckBox = Me.DataList1.Items(i).FindControl("CheckBox1")
'NameGoods
Dim NG As TextBox = Me.DataList1.Items(i).FindControl("TextBox1")
'DescriptionGoods
Dim DG As TextBox = Me.DataList1.Items(i).FindControl("TextBox2")
'Cost
Dim Cos As TextBox = Me.DataList1.Items(i).FindControl("TextBox3")

If c.Checked = True Then
txt = txt & NG.Text & " | "
productSum = productSum + CInt(Cos.Text)
End If
Next
txt = txt.Remove(0, 1)

Response.Redirect("Purchase.aspx?param=" & txt & "")
'Response.Redirect("Purchase.aspx?param1=" & productSum & "")

End Sub

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If (Not Page.IsPostBack) Then

Dim ConnectionString As String = ConfigurationSettings.AppSettings("ConnectionString")
Dim connection As New SqlConnection(ConnectionString)

connection.Open()

Dim command As New SqlCommand("Goods", connection)
command.CommandType = CommandType.StoredProcedure

Dim adapter As New SqlDataAdapter("select * from GoodsList", connection)
Dim ds As New DataSet()
adapter.Fill(ds)
Me.DataList1.DataSource = ds
Me.DataList1.DataBind()

connection.Close()
End If
End Sub

End Class
Код:
<asp:DataList ID="DataList1" runat="server" GridLines="Horizontal">
<ItemTemplate>

<asp:CheckBox ID="CheckBox1" runat="server"></asp:CheckBox>
<asp:TextBox ID="TextBox1" runat="server" Width="100px" Text='<%# DataBinder.Eval(Container.DataItem,"NameGoods") %>'></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" Width="300px" Text='<%# DataBinder.Eval(Container.DataItem,"DescriptionGoods") %>'></asp:TextBox>
<asp:TextBox ID="TextBox3" runat="server" Width="30px" Text='<%# DataBinder.Eval(Container.DataItem,"Cost") %>'></asp:TextBox>

</ItemTemplate>
</asp:DataList>
 
K

Kreol

Нужен какой-то контрол, который будет при нажатии в даталисте, ну чекбокс или нуперлинк писать данные выбраные в таблибцу. Надеюсь нормально изъяснился
 
K

Kreol

как прописать код не знаю, потому что с ВБ немного легче в 103 посте написано.
тоесть нана чтобы при нажатии допустим кнопки "В корзину" данные записывались в таблицу или еще куда-нить на хранение а потом на 2 листе они отображались
 
K

Kreol

Привет, вот изучаю хелп, как ты и говорил. Возник вопрос, в хелпе сделано через скрипт, и все работает. А вот если взять стянуть то что в скрипте в файл «.сs» то он выкидывает вот такой матюк, как исправить незнаю
Код:
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. 

Compiler Error Message: CS0117: 'ASP.default_aspx' does not contain a definition for 'Item_Command'

Source Error:


Line 18:	 <br />
Line 19:	 <br /> 
Line 20:	 <asp:DataList id="ItemsList" GridLines="Both" CellPadding="3" CellSpacing="0" OnItemCommand="Item_Command" runat="server"> 
Line 21:	 <HeaderStyle BackColor="#aaaadd"> 
Line 22:	 </HeaderStyle> 

Source File: c:\WEB\Datalist\Default.aspx	Line: 20

Сам код
Код:
<%@ Page Language="C#" AutoEventWireup="True" %> 
<%@ Import Namespace="System.Data" %> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html > 
<head> 
<title>DataList Select Example</title> 
<script runat="server"> 
ICollection CreateDataSource() 
{ 
// Create sample data for the DataList control. 
DataTable dt = new DataTable(); 
DataRow dr; 
// Define the columns of the table. 
dt.Columns.Add(new DataColumn("Item", typeof(Int32))); 
dt.Columns.Add(new DataColumn("Qty", typeof(Int32))); 
dt.Columns.Add(new DataColumn("Price", typeof(double))); 
// Populate the table with sample values. 
for (int i = 0; i < 9; i++) 
{ 
dr = dt.NewRow(); 
dr[0] = i; 
dr[1] = i * 2; 
dr[2] = 1.23 * (i + 1); 
dt.Rows.Add(dr); 
} 
DataView dv = new DataView(dt); 
return dv; 
} 
void Page_Load(Object sender, EventArgs e) 
{ 
// Load sample data only once, when the page is first loaded. 
if (!IsPostBack) 
{ 
ItemsList.DataSource = CreateDataSource(); 
ItemsList.DataBind(); 
} 
} 
void Item_Command(Object sender, DataListCommandEventArgs e) 
{ 
// Set the SelectedIndex property to select an item in the DataList. 
ItemsList.SelectedIndex = e.Item.ItemIndex; 
// Rebind the data source to the DataList to refresh the control. 
ItemsList.DataSource = CreateDataSource(); 
ItemsList.DataBind(); 
} 
</script> 
</head> 
<body> 
<form id="form1" runat="server"> 
<h3>DataList Select Example</h3> Click <b>Select</b> to select an item. 
<br />
<br /> 
<asp:DataList id="ItemsList" GridLines="Both" CellPadding="3" CellSpacing="0" OnItemCommand="Item_Command" runat="server"> 
<HeaderStyle BackColor="#aaaadd"> 
</HeaderStyle> 
<AlternatingItemStyle BackColor="Gainsboro"> </AlternatingItemStyle> 
<SelectedItemStyle BackColor="Yellow"> </SelectedItemStyle> 
<HeaderTemplate> Items </HeaderTemplate> 
<ItemTemplate> 
<asp:LinkButton id="SelectButton" Text="Select" CommandName="Select" runat="server"/>
Item <%# DataBinder.Eval(Container.DataItem, "Item") %> 
</ItemTemplate> 
<SelectedItemTemplate> 
Item: 
<asp:Label id="ItemLabel" Text='<%# DataBinder.Eval(Container.DataItem, "Item") %>' runat="server"/> 
<br /> 
Quantity: <asp:Label id="QtyLabel" Text='<%# DataBinder.Eval(Container.DataItem, "Qty") %>' runat="server"/> 
<br /> 
Price: <asp:Label id="PriceLabel" Text='<%# DataBinder.Eval(Container.DataItem, "Price", "{0:c}") %>' runat="server"/> 
</SelectedItemTemplate> 
</asp:DataList> 
</form> 
</body> 
</html>
 
K

Kreol

гы, с этим разобрался, нана было написать еще
Код:
DataList1.ItemCommand += new DataListCommandEventHandler(this.Item_Command);

но возникла другая проблема, при нажатии того что прописали, происходит только выделение желтым цветом в данном случае, а сама обработка void Item_Command(Object sender, DataListCommandEventArgs e) не происходит, почему???
Код:
 void Item_Command(Object sender, DataListCommandEventArgs e)
{

string ConnectionString = ConfigurationSettings.AppSettings.Get("ConnectionString");
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
//p.242 Разработка Web приложений
int id_goods = Convert.ToInt32("TextBox1.Text");
connection.Open();
SqlCommand command2 = new SqlCommand("Insert into Purchase " + " id_goods values @id_goods", connection);
command2.Parameters.AddWithValue("@id_goods", id_goods);
SqlDataReader adapter;
adapter = command2.ExecuteReader();
}
finally
{
connection.Close();
}
}
 
K

Kreol

в посте 108 написан код работающий, с онкоманд, но там все написано в скрипте, а мне так не нужно. Если выташить код из скрипта в файл кс, то начинает матюкаться что неправильно написано, как в посте 108 ерор, 2) не происходит обработка самого онитемкомманд
 
K

Kreol

незнаю: вроде все пересмотрел, вот код
Код:
using System;
using System.IO;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Drawing;
using System.Drawing.Imaging;

public partial class Main : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

if (!Page.IsPostBack)
{
DataList1.ItemCommand += new DataListCommandEventHandler(this.Item_Command);
string ConnectionString = ConfigurationSettings.AppSettings.Get("ConnectionString");
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
//p.242 Разработка Web приложений
connection.Open();
SqlCommand command = new SqlCommand("AddG", connection);
SqlDataAdapter adapt = new SqlDataAdapter("SELECT id_goods,comment from AddG", connection);
DataTable dataTable = new DataTable();
adapt.Fill(dataTable);
DataList1.DataSource = dataTable;	  
DataList1.DataBind();

}
finally
{
connection.Close();
}

}

}
void Item_Command(Object sender, DataListCommandEventArgs e)
{

string ConnectionString = ConfigurationSettings.AppSettings.Get("ConnectionString");
SqlConnection connection = new SqlConnection(ConnectionString);
try
{
//p.242 Разработка Web приложений
int id_goods = Convert.ToInt32("TextBox1.Text");
connection.Open();
SqlCommand command2 = new SqlCommand("Insert into Purchase " + " id_goods values @id_goods", connection);
command2.Parameters.AddWithValue("@id_goods", id_goods);
SqlDataReader adapter;
adapter = command2.ExecuteReader();
}
finally
{
connection.Close();
}
} 
}

Код:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Main.aspx.cs" Inherits="Main" %>

<%@ Import Namespace="System.Data" %> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body bgcolor="#009966">
<form id="form1" runat="server">
<div>
<asp:Image ID="Logo" runat="server" ImageUrl="~/Images/Menu/logo-auto.gif"/>
<Table style="height: auto; Width: auto" border="0">  


<!--Menu -->
<td style="top; height: 100px; Width: 155px" align="justify" >

<asp:ImageButton ID="ImgBtn_Main" runat="server" ImageAlign="Top" ImageUrl="~/Images/Menu/Main.gif" PostBackUrl="~/Main.aspx"></asp:ImageButton>
<asp:ImageButton ID="ImgBtn_Login" runat="server" ImageUrl="~/Images/Menu/Login.gif" PostBackUrl="~/Default.aspx"></asp:ImageButton>
<asp:ImageButton ID="ImgBtn_ShoppingCart" runat="server" ImageUrl="~/Images/Menu/ShoppingCart.gif" PostBackUrl="~/ShoppingCart.aspx"></asp:ImageButton>
<asp:ImageButton ID="ImgBtn_Purchase" runat="server" ImageUrl="~/Images/Menu/Purchase.gif" PostBackUrl="~/Purchase.aspx"></asp:ImageButton>
<asp:ImageButton ID="ImgBtn_Order" runat="server" ImageUrl="~/Images/Menu/Order.gif" PostBackUrl="~/Order.aspx"></asp:ImageButton>
<asp:ImageButton ID="ImgBtn_Add_Good" runat="server" ImageUrl="~/Images/Menu/Add Good.gif" PostBackUrl="~/AddGoods.aspx"></asp:ImageButton>
</td> 

<!--End Menu -->
<td>


<asp:DataList id="DataList1" GridLines="Both" CellPadding="3" CellSpacing="0" runat="server"> 

<HeaderStyle BackColor="#aaaadd"> 
</HeaderStyle> 
<AlternatingItemStyle BackColor="Gainsboro"> </AlternatingItemStyle> 
<SelectedItemStyle BackColor="Yellow"> </SelectedItemStyle> 
<HeaderTemplate> Items </HeaderTemplate> 
<ItemTemplate>

<asp:LinkButton id="SelectButton" Text="В корзину" CommandName="Select" runat="server"/>
<asp:HyperLink ID="HyperLink_Image" runat="server" ImageURL='<%# Eval("id_goods", "~/Handler_View_Image.ashx?id_goods={0}" )%>' ></asp:HyperLink>
<asp:Label ID="Lbl_comment" runat="server" Text='<%# Eval("comment") %>'></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("id_goods")%>' Visible="true"></asp:TextBox>
</ItemTemplate>
<SelectedItemTemplate> 
<asp:HyperLink ID="HyperLink_Image" runat="server" ImageURL='<%# Eval("id_goods", "~/Handler_View_Image.ashx?id_goods={0}" )%>' ></asp:HyperLink>
<asp:Label ID="Lbl_comment" runat="server" Text='<%# Eval("comment") %>'></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Eval("id_goods")%>' Visible="true"></asp:TextBox>
</SelectedItemTemplate> 
</asp:DataList>
</td>
</Table>
</div>
</form>
</body>
</html>

не попадает на обработку и все
 
Мы в соцсетях:

Обучение наступательной кибербезопасности в игровой форме. Начать игру!