2014-11-01 2 views
0

Я разрабатываю простой сайт для выставления счетов. База данных находится в Access 2013 формата * .mdb. И используемый язык C# .NETУмножить 2 столбца и сгенерировать итоговые данные из таблицы asp

Теперь У меня есть таблица в файле Home.aspx

<fieldset> 
     <asp:Table ID="DisplayTable" runat="server" CssClass="pure-table-horizontal" align="center"></asp:Table> 
    </fieldset> 

Эта таблица Затопленные во время выполнения с помощью следующего кода в Home.aspx.cs

protected void Page_Load(object sender, EventArgs e) 
{ 
    //Use a string variable to hold the ConnectionString. 
    string connectString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source= C:\Users\Raunaq\Documents\Visual Studio 2013\WebSites\BookStore\Database\Database.mdb"; 
    //Create an OleDbConnection object, 
    //and then pass in the ConnectionString to the constructor. 
    OleDbConnection cn = new OleDbConnection(connectString); 

    //Open the connection. 
    cn.Open(); 

    //Use a variable to hold the SQL statement. 
    string selectString = "SELECT Book_ID, Book_Name, Cost FROM Book_Details"; 

    //Create an OleDbCommand object. 
    //Notice that this line passes in the SQL statement and the OleDbConnection object 
    OleDbCommand cmd = new OleDbCommand(selectString, cn); 

    //Send the CommandText to the connection, and then build an OleDbDataReader. 
    //Note: The OleDbDataReader is forward-only. 
    OleDbDataReader reader = cmd.ExecuteReader(); 

    //Set a table width. 
    DisplayTable.Width = Unit.Percentage(50.00); 
    //Create a new row for adding a table heading. 
    TableRow tableHeading = new TableRow(); 

    //Create and add the cells that contain the Customer ID column heading text. 
    TableHeaderCell customerIDHeading = new TableHeaderCell(); 
    customerIDHeading.Text = "ID"; 
    customerIDHeading.HorizontalAlign = HorizontalAlign.Left; 
    tableHeading.Cells.Add(customerIDHeading); 

    //Create and add the cells that contain the Contact Name column heading text. 
    TableHeaderCell contactNameHeading = new TableHeaderCell(); 
    contactNameHeading.Text = "Book Name"; 
    contactNameHeading.HorizontalAlign = HorizontalAlign.Left; 
    tableHeading.Cells.Add(contactNameHeading); 

    //Create and add the cells that contain the Phone column heading text. 
    TableHeaderCell phoneHeading = new TableHeaderCell(); 
    phoneHeading.Text = "Price"; 
    phoneHeading.HorizontalAlign = HorizontalAlign.Left; 
    tableHeading.Cells.Add(phoneHeading); 

    TableHeaderCell quan = new TableHeaderCell(); 
    quan.Text = "Quantity"; 
    quan.HorizontalAlign = HorizontalAlign.Left; 
    tableHeading.Cells.Add(quan); 


    DisplayTable.Rows.Add(tableHeading); 

    //Loop through the resultant data selection and add the data value 
    //for each respective column in the table. 
    while (reader.Read()) 
    { 
     TableRow detailsRow = new TableRow(); 
     TableCell customerIDCell = new TableCell(); 
     customerIDCell.Text = reader["Book_ID"].ToString(); 
     detailsRow.Cells.Add(customerIDCell); 

     TableCell contactNameCell = new TableCell(); 
     contactNameCell.Text = reader["Book_Name"].ToString(); 
     detailsRow.Cells.Add(contactNameCell); 

     TableCell phoneCell = new TableCell(); 
     phoneCell.Text = reader["Cost"].ToString() + " " + "&#8377;"; 
     detailsRow.Cells.Add(phoneCell); 

     TableCell quanti = new TableCell(); 
     TextBox tb = new TextBox(); 
     tb.ID = reader["Book_ID"].ToString(); 
     tb.Text = "0"; 
     tb.Width = 66; 
     quanti.Controls.Add(tb); 
     detailsRow.Cells.Add(quanti); 

     DisplayTable.Rows.Add(detailsRow); 

    } 

    //Close the reader and the related connection. 
    reader.Close(); 
    cn.Close(); 
    Panel1.Visible = false; 
} 

Теперь у меня есть кнопка с именем «Рассчитать», и я хочу сгенерировать общую сумму на основе столбцов «Цена и количество». Я пробовал много вещей, но ничего не работает до сих пор.

Пожалуйста, помогите мне. Скажите, пожалуйста, если вам нужно что-нибудь еще, чтобы лучше понять мою проблему.

спасибо. Задача решена. Решение

for (int i=1;i<row_count;i++) 
    { 
     TextBox tc = (TextBox)DisplayTable.FindControl("tb" + i); 
     int q1 = Convert.ToInt32(tc.Text); 
     TableCell tcc = (TableCell)DisplayTable.FindControl("cost" + i); 
     char[] trimchar; 
     string trim = " " + "&#8377;"; 
     trimchar = trim.ToCharArray(); 
     string a1 = tcc.Text.TrimEnd(trimchar); 
     int a = Int32.Parse(a1); 
     total_amt = q1 * a + total_amt; 
    } 
    Amount = total_amt; 
    Label1.Text = Amount.ToString() + "&#8377;"; 

ответ

0

У меня есть создать MCVE пример. Короче говоря, установите правильный идентификатор для отдельного TableCell и получите каждое значение ячейки, соответствующее столбцу, с помощью FindControl.

ASPX код

<asp:Table ID="tbl" runat="server" /> 
<asp:Button ID="btn" runat="server" Text="Submit" OnClick="btn_Click" /> 

стороны сервера код

protected void Page_Load(object sender, EventArgs e) 
{ 
    BuildControls(); 
} 
public void BuildControls() 
{ 
    TableRow tr = new TableRow(); 
    TableCell tc = new TableCell(); 
    tc.Text = "hello world"; 
    tc.ID = "h1"; 
    tr.Cells.Add(tc); 

    tc = new TableCell(); 
    tc.Text = "hello world1"; 
    tc.ID = "h2"; 
    tr.Cells.Add(tc); 

    tbl.Rows.Add(tr); 
} 

protected void btn_Click(object sender, EventArgs e) 
{ 
    TableCell c1 = (TableCell)tbl.FindControl("h1"); 
    string val1 = c1.Text; 
    TableCell c2 = (TableCell)tbl.FindControl("h2"); 
    string val2 = c2.Text; 
} 

Примечание: Я строй таблицы в стороне сервера кода, и когда я делаю postback, я получаю значение с помощью FindControl.

Ниже приведен вывод для этого.

enter image description here

+0

Здравствуйте, Но мой стол динамичен. Таким образом, это создает большие проблемы, так как не совсем точно фиксирует, сколько строк оно будет иметь. – user2923365

+1

Спасибо, после нескольких модификаций я наконец смог это сделать. – user2923365

0

Добавить атрибут к количеству клетки как

TableCell quanti = new TableCell(); 
    TextBox tb = new TextBox(); 
    quanti.Attributes.Add("data_qty","100"); 
    tb.ID = reader["Book_ID"].ToString(); 
    tb.Text = "100"; 
    tb.Width = 66; 
    quanti.Controls.Add(tb); 
    detailsRow.Cells.Add(quanti); 

Для расчета, первая строка заголовка. поэтому нам нужно пропустить его и пропустить строки в таблице

qty.Text = DisplayTable.Rows.Cast<TableRow>().ToList<TableRow>().Skip(1).Select(g => Convert.ToInt64(g.Cells[2].Text.Split(' ')[0].ToString()) * Convert.ToInt64(g.Cells[3].Attributes["data_qty"])).Sum().ToString(); 
+0

Hello Pradeep. Текстовое поле предназначено для конечного пользователя для ввода количества. – user2923365

Смежные вопросы